1
votes

I'm using Axios library to make an API call in my React application.I call the API and then populate a table using React.

My Axios call is as follows:

     axios({
      method: 'get',
      url: DataURL,
      headers: {
        'Content-Type' : 'application/json',
        'Id': user.Id,
        'Name' : user.Name,
        'api-token' : user.access_token,
        'clientId' : 'web',
    },
    responseType: 'json',
  })
    .then((response) => {
      this.setState({ tableData: response.data });
    });

However I get this error:

XMLHttpRequest cannot load MY API URL Response for preflight has invalid HTTP status code 400

The same was working in my dev environment where I wasn't adding any headers, however after migrating to new env which required me to add headers, Im getting the above error. My question is, is this a client side issue(like wrong header format etc) or is it something to do with server side handling of the API call?

1
*“Response for preflight has invalid HTTP status code 400”*—the preflight is an OPTIONS request and as far as understand things, there’s never any good reason a server should respond to an OPTIONS request with a 400. It indicates some misconfiguration—or lack of configuration—on the server. Anyway, the preflight OPTIONS request is something that browsers do on their own automatically, so from your frontend code, you have no control over how that OPTIONS is formulated. So there’s nothing you can do to fix it. Instead, the server needs to fixed to respond to it correctlysideshowbarker
And to be clear, the reason your browser’s sending that OPTIONS request to begin with is because your code adds the 'api-token', 'clientId', 'Name', 'Id', and 'Content-Type :'application/json' request headers. Even adding any just one of those headers to the request will trigger browsers to do a preflight. See developer.mozilla.org/en-US/docs/Web/HTTP/…. So if you want to make this request work from frontend JavaScript code running in browsers, the server the code’s making the request to must be fixed to respond to that preflight OPTIONS correctlysideshowbarker

1 Answers

1
votes

I think this is a server-side issue. If you are using node in the background you need CORS as a middleware (https://www.npmjs.com/package/cors). For other server solutions there are of course also cors request handler.