3

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.'
}

Sunny
  • 81
  • 1
  • 9
  • if you fixed the problem? uh.. congrats? but also change your api key since you've sent it publicly ;-; – The Bomb Squad Jun 18 '22 at 11:55
  • Oh, Thanks, I've changed it now. I keep forgetting about it. I'll watch out for these sorts of things from the next time. – Sunny Jun 20 '22 at 07:46
  • @Sunny can you post an answer, please? - I don't understand what was the solution. – Marco Aurelio Fernandez Reyes Aug 02 '22 at 21:44
  • @MarcoAurelioFernandezReyes To be honest I don't know what actually caused this problem. The solution I found was passing the user Agent in headers as parameter. And It was working even if i had provided user Agent string myself. But the following code i've posted of the solution is taking the userAgent from user. Though my thoughts on the problem is The API provider was not allowing a machine to fetch any data with unrecognized userAgent. ( I don't know if this was the case). Hope i answered your question to some extent. – Sunny Aug 03 '22 at 11:16
  • 1
    @Sunny thank you for your reply. [You can post the answer](https://stackoverflow.com/help/self-answer) in the section called "Your Answer" - under your question, there, you can [accept it](https://stackoverflow.com/help/accepted-answer). – Marco Aurelio Fernandez Reyes Aug 03 '22 at 14:22

1 Answers1

2

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");
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Sunny
  • 81
  • 1
  • 9