如何解决Azure 函数 nodejs 返回 200 OK,响应为空
我正在使用 Azure 函数来做一些工作,一切都很好,只是我无法从结果中获取响应正文:
module.exports = async function (context,req) {
context.log('JavaScript HTTP trigger function processed a request.');
const fetch = require('node-fetch');
const myURL= (req.query.apiURL|| (req.body && req.body.apiURL));
fetch(myURL)
.then(data => {
if (!data.ok) {
throw new Error('some error occurred');
}
return data;
})
.then(data => data.text())
.then(text =>
context.res = {
body: text //here is the problem
});
}
function.json
{
"bindings": [
{
"authLevel": "anonymous","type": "httpTrigger","direction": "in","name": "req","methods": [
"get","post"
]
},{
"type": "http","direction": "out","name": "res"
}
]
}
修复
空响应与使用不带 async
的 await
方法有关
所以只需删除 async 或将 await 与 async 一起使用。
解决方法
增强的 async/await,@BowmanZhu 版本
const fetch = require('node-fetch');
module.exports = async function (context,req) {
try{
context.log('JavaScript HTTP trigger function processed a request.');
const myURL= (req.query.apiURL || (req.body && req.body.apiURL)),fetchResp = await fetch(myURL),resBody =fetchResp.text();
/** TODO LOGIC **/
context.res = {
status:200,body: resBody
};
}catch(err){
context.res = {
status:500,body: err.message
};
}
}
,
请不要使用 lambda 表达式,你需要像这样执行它们,就会有结果(不确定你在做什么,但我认为你的设计有问题):
const fetch = require('node-fetch');
module.exports = async function (context,req) {
context.log('JavaScript HTTP trigger function processed a request.');
const myURL= (req.query.apiURL|| (req.body && req.body.apiURL));
fetch(myURL)
.then(
//some logic here.
context.res = {
body: "This is a test." //here is the problem
}
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。