使用 Azure Functions,您需要做什么才能从用 node.js 编写的函数返回正文中的 JSON 对象?我可以轻松返回一个字符串,但是当我尝试返回如下所示的 json 对象时,我似乎没有返回任何内容。
context.res = {
body: jsonData,
contentType: 'application/json'
};
最佳答案
基于我最近的测试(2017 年 3 月)。您必须显式地将内容类型添加到响应 header 才能获取 json,否则数据会在浏览器中显示为 XML。
"Content-Type":"application/json"
res = {
status: 200, /* Defaults to 200 */
body: {message: "Hello " + (req.query.name || req.body.name)},
headers: {
'Content-Type': 'application/json'
}
};
完整示例如下:
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);
};
关于json - 如何使用 Node.js 从 Azure 函数返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37152658/