Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js : POST - Request Method: OPTIONS Status Code: 403 Forbidden

We have the following setup :

Front end code : REACT (Hosted using express js) (lets call this www.domainA.com)
Backend        : .NET WEB API (Hosted in IIS 7.5) (lets call this www.domainB.com)

The domain of the FE app is making the request to GET data and POST data to the web api.

The GET is working perfectly, however whenever I am trying to POST data to the web API, its throwing the following error :

Request URL: http://www.domainB.com/api/postdataoperation
Request Method: OPTIONS
Status Code: 403 Forbidden

I have looked at many CORS articles and went ahead and setup HTTPResponseHeaders in IIS as follows :

Access-Control-Allow-Methods : POST,GET,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin  : http://www.domainA.com

The post request from react solution is as follows :

axios.post(`http://www.domainB.com/api/postdataoperation`, {userId});
like image 688
Murtaza Mandvi Avatar asked Feb 05 '23 00:02

Murtaza Mandvi


1 Answers

The issue is that your server is not configured to respond to OPTIONS requests with the correct response status, 2xx success status.

The GET is working because it is not making a preflight request, as it meets the criteria to be a simple request as defined by the CORS documentation

On the other hand, the POST request meets the criteria to be a Preflighted request, meaning a preflight OPTIONS request should be made first.

In short, you have correctly setup the CORS response headers, but the server is not configured to respond with a 2xx response for OPTIONS method requests(commonly 200 status).

The server must respond to OPTIONS requests with a 2xx success status—typically 200 or 204.

If the server doesn’t do that, it makes no difference what Access-Control-* headers you have it configured to send. And the answer to configuring the server to handle OPTIONS requests in the right way—to send a 200 or 204 success message—depends on what server software it’s running

Borrowing the solution from this answer, do this on your backend, .NET WEB API:

In your BaseApiController.cs:

We do this to allow the OPTIONS http verb

public class BaseApiController : ApiController
  {
    public HttpResponseMessage Options()
    {
      return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
    }
}

References

Preflighted requests

response for preflight 403 forbidden

Note

Running a nodejs server on domainA.com is irrelevent. The "axios" library can be used either to a) make XMLHttpRequests from the browser or b) make http requests from node.js. In this case it is the first option, the "axios.post" to domainB is done through a XMLHttpRequest from the browser, that `s why you get a preflighted request at domainB.com.

like image 148
Jannes Botis Avatar answered Feb 08 '23 12:02

Jannes Botis