Chr*_*ger 13 json azure node.js azure-functions
使用Azure Functions,您需要做什么才能从node.js中编写的函数返回正文中的JSON对象?我可以轻松返回一个字符串,但是当我尝试返回如下所示的json对象时,我似乎没有返回任何内容.
context.res = {
body: jsonData,
contentType: 'application/json'
};
Run Code Online (Sandbox Code Playgroud)
spo*_*oky 24
根据我最近的测试(2017年3月).您必须向响应标头显式添加内容类型以使json返回,否则数据在浏览器中显示为XML.
"内容类型":"应用/ JSON"
res = {
status: 200, /* Defaults to 200 */
body: {message: "Hello " + (req.query.name || req.body.name)},
headers: {
'Content-Type': 'application/json'
}
};
Run Code Online (Sandbox Code Playgroud)
完整示例如下:
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
context.log(context);
if (req.query.name || (req.body && req.body.name)) {
res = {
// status: 200, /* Defaults to 200 */
body: {message: "Hello " + (req.query.name || req.body.name)},
headers: {
'Content-Type': 'application/json'
}
};
}
else {
res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done(null, res);
};
Run Code Online (Sandbox Code Playgroud)
如果您的数据是JS对象,那么这应该可以正常工作,例如
module.exports = function(context, req) {
context.res = {
body: { name: "Azure Functions" }
};
context.done();
};
Run Code Online (Sandbox Code Playgroud)
这将返回application/json响应.
如果您将数据放在json 字符串中,则可以:
module.exports = function(context, req) {
context.res = {
body: '{ "name": "Azure Functions" }'
};
context.done();
};
Run Code Online (Sandbox Code Playgroud)
哪个会返回一个application/json响应,因为它会嗅到它是有效的json.
| 归档时间: |
|
| 查看次数: |
11305 次 |
| 最近记录: |