Home > Mobile >  'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doe
'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doe

Time:07-07

I've created an API and have the following within the WebApiConfig.cs:

var cors = new EnableCorsAttribute("http://localhost:3000", "*", "*");
config.EnableCors(cors);

I'm able to access it with my React application but I've created a new method within one of the controllers and restarted the API. When I tested it in Postman by sending a POST request it worked fine. However I'm now getting the error in the title when I try to access it using my React application. All other methods within the controller work fine. It's just this new one that is causing issues:

Accessing new method in React

        const requestOptions = {
            method: 'post',
            headers: { "Content-type":"application/json",
                       "Accept":"*/*",
                       "Accept-Encoding":"gzip, deflate, br" },
            body: JSON.stringify({ Data: this.props.data})
        };
        fetch("http://localhost:9074/Output/EditByMultipleIDs?varA="   this.state.varA   "&varB="   this.state.varB   "&varC="   this.state.varC, requestOptions)
            .then(response => response.json());

varA and varC are just a string of comma separated ids and varB is just an integer.

One which works from the same controller

        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ Data:this.props.data})
        };
        fetch("http://localhost:9074/Output/EditByID?varA="   this.state.varA   "&varB="   this.state.varB, requestOptions)
             .then(response => response.json());

here varA and varB are just integers.

I had tried to add in extra headers but that didn't seem to have worked and had also tried to add in [EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")] into the controller but that didn't help either.

I've noticed that if I remove [System.Web.Mvc.HttpPost] from the EditByMultipleIDs method within the controller then I'm able to hit the method without any CORS issue but then my model variable is null as nothing is passed into it from the body.

Below are the declaration for both methods within the controller:

[System.Web.Mvc.HttpPost]
        public ActionResult EditByMultipleIDs(string varA, [FromBody] DTO model, int varB, string varC)
        { //... Do stuff}

[System.Web.Mvc.HttpPost]
        public ActionResult EditByID(int varA, [FromBody] DTO model, int varB)
        {//... Do stuff}

Also when I open the link in chrome I get:

error in chrome

I'm not sure if that's because the body data is lost so it's not able to complete the request or what but yeah...

EDIT 1: Actual Requests being made:

General

Request URL: http://localhost:9074/Output/EditByMultipleIDs?varA=55279,55280&varB=3&varC=393,394
Request Method: OPTIONS
Status Code: 404 Not Found
Remote Address: [::1]:9074
Referrer Policy: strict-origin-when-cross-origin

Response Headers

Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Cache-Control: private
Content-Length: 4500
Content-Type: text/html; charset=utf-8
Date: Mon, 04 Jul 2022 08:59:48 GMT
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcbW5hemlyXERlc2t0b3BcQWZ0b25cUnVsZXMgRW5naW5lXFJ1bGVFbmdpbmVBUEkgLSBDb3B5XFJ1bGVFbmdpbmVBUElcT3V0cHV0XEVkaXRCeU11bHRpcGxlSURz?=

Request Headers

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:9074
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

CodePudding user response:

I had found the solution here: Handling CORS Preflight requests to ASP.NET MVC actions

Just need to add in:

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) &&
        Request.HttpMethod == "OPTIONS") {
        Response.Flush();
    }
}

into Global.asax file so that it sends an empty response whenever it gets a OPTIONS request

  • Related