我正在使用 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 一起使用。
答案 0 :(得分:1)
增强的 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
};
}
}
答案 1 :(得分:0)
请不要使用 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
}
);
}