Bishan
Bishan

Reputation: 15702

ENOTFOUND when making API call from Azure Functions NodeJS

I am trying to make an API call using Azure Functions. But I am getting below error.

{
  "errno": "ENOTFOUND",
  "code": "ENOTFOUND",
  "syscall": "getaddrinfo",
  "hostname": "https://jsonplaceholder.typicode.com",
  "host": "https://jsonplaceholder.typicode.com",
  "port": "80"
}

My Code

var http = require('http');

module.exports = function (context) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var options = {
        host: 'https://jsonplaceholder.typicode.com',
        port: '80',
        path: '/users',
        method: 'GET'
    };

    // Set up the request
    var req = http.request(options, (res) => {
        var body = "";

        res.on("data", (chunk) => {
            body += chunk;
        });

        res.on("end", () => {
            context.res = body;
            context.done();
        });
    }).on("error", (error) => {
        context.log('error');
        context.res = {
            status: 500,
            body: error
        };
        context.done();
    });
    req.end();
};

How could I solve this?

Upvotes: 2

Views: 2519

Answers (1)

Sandeep Patel
Sandeep Patel

Reputation: 5148

You made a few common mistakes:

  • You are using http module for https URL.
  • Change host value to jsonplaceholder.typicode.com
  • For https protocol port should be 443

Change options as below:

For http:

var options = {
        host: 'jsonplaceholder.typicode.com',
        port: '80',
        path: '/users',
        method: 'GET'
    };

For https:

Use https module to make request and options object should be like this

 var options = {
            host: 'jsonplaceholder.typicode.com',
            port: '443',
            path: '/users',
            method: 'GET'
    };

Demo:https://repl.it/repls/RepentantGoldenrodPriority

Upvotes: 1

Related Questions