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.'
}
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");
});