2

I am using News API in ReactJS for fetching news using fetch API.

CODE FRAGMENT

const url = `https://newsapi.org/v2/top-headlines?country=in&category=${this.props.category}&pageSize=${this.state.pageSize}&page=${this.state.page}`;
let data = await fetch(url);

But when I run it on the localhost, it gave an error 400 saying:

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

When I searched the same on Stack Overflow, I got a link of a similar problem here:

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

Then I added the User-Agent header in the fetch API's argument:

CODE FRAGMENT

headers = new Headers({
        "X-Api-Key": this.apiKey,
        "User-Agent": navigator.userAgent
    });
const url = `https://newsapi.org/v2/top-headlines?country=in&category=${this.props.category}&pageSize=${this.state.pageSize}&page=${this.state.page}`;
let data = await fetch(url, {
            headers: this.headers
        });

But still it shows the same error:

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

This error is asking for "User-Agent" in the request header, but it is already there! When I looked into the network section of the chrome browser.

Screenshot of the network section of chrome

So, what's exactly the problem is? And how to solve this issue?

VLAZ
  • 26,331
  • 9
  • 49
  • 67

1 Answers1

1

I am having a similar problem. So far I have been able to pass in one of the web browser User-Agents from the Mozilla Developer websites.

function webCall(url,method,headers,postBody,callBack){

   /* build options */
   var options = {
       method: method,
       uri: url, 
       headers: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59',
       body: postBody
   }
   ...
};

This is still in development; however, I was able to return results from my newsapi.org pull.

Edit: For reference, I am using the old 'Requests' npm library (legacy requirement). So I make my request like so:

request(options, function handleResponse(err, response, body){
   var errMessage = null;
   var headers = {};
   
   if(err) {
      errMessage='HTTP ERROR: ' + err;
   }
   else {
      headers = response.headers;
      if(response.statusCode!=200){
         errMessage='HTTP ' + response.statusCode + ' ERROR: ' + err;
      }
   }
});
rcart
  • 43
  • 5
  • So how can I fetch data from the link. Can you show me a sample code (like the one written in the question). I was unable to figure out what to do by your answer. – Neeraj-Kumar-Coder Jul 23 '22 at 13:55