javascriptnode.jsazure-functionshttpresponseazure-http-trigger

Azure function nodejs return 200 OK with empty response


I'm using an Azure function to do some work, all is good except that I can not get the response body from the result:

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"
    }
  ]
}

Fix

The empty response was related to using an async method without await so just remove the async or use await with async.


Solution

  • Enhanced async/await, version of @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
                         };
         }
        }