Search code examples
javascriptasp.netasp.net-corecorsfetch-api

'no Access-Control-Allow-Origin in the request header


I have created an API with ASP.NET Core, in Program.cs I specified the allowed origins policy as shown:

var origins = 'allowedOrigins';
builder.Services.AddCors((options) => {
  options.AddPolicy(origins, (policy) => {
    policy
      .WithOrigins(
        'http://10.9.8.50:80',
        'http://10.9.8.50:81',
        'http://10.9.8.50:7087',
        'http://10.9.8.50:5000'
      )
      .AllowAnyHeader()
      .AllowAnyMethod();
  });
});

app.UseCors(origins);

and I am using basic JavaScript fetch method to call POST

async function postData(url = '', data = {}) {
  let value;
  const p = await fetch(url, {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
    },
    redirect: 'follow',
    referrerPolicy: 'no-referrer',
    body: JSON.stringify(data),
  }).then((response) => (value = response.text()));
  return value;
}

recently, the server starting to act weird after I tried to publish some modifications to the logic of one of the controllers. I started getting 'no Access-Control-Allow-Origin in the request header'.

I am working with IIS 10 server, I tried to inject the CORS policy in the web.config but I started getting an error saying only one value was allowed in Access-Control-Allow-Origin.

I am wondering what might be the issue that started all of this, and what could the solution be.

Thanks

EDIT: I added the following lines to my web.config file

<cors enabled="true" failUnlistedOrigins="false">
        <add origin="*" allowed="true" />
</cors>

And now I am getting the following error:

has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.


Solution

  • Adding the following lines to my API's web.config file solved the problem.

    <cors enabled="true" failUnlistedOrigins="false">
        <add origin="*" allowed="true">
            <allowHeaders allowAllRequestedHeaders="true"/>
        </add>
    </cors>