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

后端 未结 3 1999
时光说笑
时光说笑 2021-01-17 19:39

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          


        
3条回答
  •  有刺的猬
    2021-01-17 20:33

    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.

提交回复
热议问题