Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Agent Missing error when making a get request to an API

I am trying to make a Project using news API and I keep getting userAgentMissing error. I've tried few things but I couldn't figure out what I am doing wrong. i've tried using https.request method as well but result was the same.

app.get("/", function (req, res) {
let url = "https://newsapi.org/v2/top-headlines?country=in&apiKey=xxxxx";

https.get(url, function (response) {
    console.log(response.statusCode);
    response.on('data', function (data) {
        const recievedData = JSON.parse(data);
        console.log(recievedData); 
    });
  });
});

And here's the error I am getting.

400
{
status: 'error',
code: 'userAgentMissing',
message: 'Please set your User-Agent header to identify your application. Anonymous requests are not allowed.'
}

like image 296
Sunny Avatar asked Sep 06 '25 03:09

Sunny


1 Answers

Passing the User agent in headers as parameters worked for me. Also when using fetch method i didn't encountered this problem.

app.get("/", function (req, res) {
  const userAgent = req.get('user-agent');
  const options = {
  host: 'newsapi.org',
  path: '/v2/top-headlines?country=in&apiKey=xxxxxxxx',
  headers: {
    'User-Agent': userAgent
  }
}
https.get(options, function (response) {
let data;
  response.on('data', function (chunk) {
      if (!data) {
          data = chunk;
      }
      else {
          data += chunk;
      }
  });
  response.on('end', function () {
      const newsData = JSON.parse(data);
      console.log(newsData);
    });
  });
  res.send("hello");
});
like image 139
Sunny Avatar answered Sep 07 '25 22:09

Sunny