1

我正在使用 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 因此只需删除异步或将 await 与异步一起使用。

4

2 回答 2

1

增强的异步/等待,@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
                     };
     }
    }
于 2021-01-19T18:03:56.790 回答
1

请不要使用 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
            }
        );      
}
于 2021-01-19T15:26:10.777 回答