Tarek
Tarek

Reputation: 43

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.

Upvotes: 1

Views: 2899

Answers (3)

suneel simhadri
suneel simhadri

Reputation: 32

In my case, I didn't updated the environment variable for database.

Upvotes: 0

Muhamed Salih
Muhamed Salih

Reputation: 156

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
                     };
     }
    }

Upvotes: 1

suziki
suziki

Reputation: 14080

Please do not use lambda expressions, you need to execute them like this, and there will be a result (not sure what you are doing, but I think there is something wrong with your design):

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
            }
        );      
}

Upvotes: 1

Related Questions