简体   繁体   中英

Access to fetch at *** from origin *** has been blocked by CORS policy: No 'Access-Control-Allow-Origin'

I have error

Access to fetch at ' http://localhost:5000/admin/authenticate ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My ApiManager

function login(username, password) {
    const requestOptions = {
        method: 'POST',
        headers: {    
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*' },
        body: JSON.stringify({ username, password })};

    return fetch(`http://localhost:5000/admin/authenticate`, requestOptions)
        .then(handleResponse)
        .then(user => {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('user', JSON.stringify(user));
            return user;
        }
    );
}

In Backend Asp.Net Core 2.2 (Startup.cs) I write:

services.AddCors(options =>
{
    options.AddPolicy(
        _corsName,
        builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials(); });}
);

i tried anerco's answer but it didn't work for me, i found this article , it has a very similar solution but with .SetIsOriginAllowed(origin => true) added and .AllowAnyOrigin() removed.

So you should add this code to your Configure method in startup class :

app.UseCors(x => x
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .SetIsOriginAllowed(origin => true) // allow any origin
                    .AllowCredentials()); // allow credentials

I recommend reading the article to get a better understanding of all of this, it's very short and straight to the point.

Try this:

on Startup.cs => Confirgure add:
     app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());

Hi I'm new on this topic but because I've got this error last week I tried enabling options method and the first part resolved . This error happens due to policy and security issues but now I refer you to get the status code and in my case it was 405 error which means now we have to change our headers in the request to allow all methods and origins (no way ) but it doesn't help me out.

So I figured out that I have enabled cookie encryption and session (wide of the point) in my app for my API therefore I disabled them and cleared browser cookie as well .

So try using these:

  1. Clear your cookies and add Access-Control-Allow-Origin': '*' by Mod Header extension and try again to check the fix . mod header - your header (client)

  2. Try using a middle interface to control your request and guide them into the special rules

    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      next();
    });

According to this site : https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

If your server is express.js based, add these lines to the server:

app.use(function (req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
})

FOR NODE EXPRESS GRAPHQL RESTAPI Add this header middleware to avoid CORS and any POST or OPTIONS error

app.use((req, res, next) => {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader(
        "Access-Control-Allow-Methods",
        "OPTIONS, GET, POST, PUT, PATCH, DELETE"
      );
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
      if (req.method === "OPTIONS") {
        return res.sendStatus(200);
      }
      next();
    });

In my case, I was trying to make a blob from an image stored on the API (the server) so the URL was pointing to that resource, in that API's program.cs class, I already had a CORS policy, but I'd get the exact error as you said. After I read the Microsoft docs (read the first paragraph that you see) about this issue, it is said that if you want to access a resource on the server, by using JavaScript (which is what I was trying to do), then you must call the app.UseCors(); BEFORE the app.UseStaticFiles();which is typically the opposite.

My program.cs :

const string corsPolicyName = "ApiCORS";

builder.Services.AddCors(options =>
{
    options.AddPolicy(corsPolicyName, policy =>
    {
        policy.WithOrigins("https://localhost:7212");
    });
});

...

var app = builder.Build();

app.UseSwagger();

app.UseSwaggerUI(settings =>
{
    settings.DisplayRequestDuration();
    settings.EnableTryItOutByDefault();
});

app.UseHttpsRedirection();

app.UseCors(corsPolicyName); // 👈 This should be above the UseStaticFiles();

app.UseStaticFiles(); // 👈 Below the UseCors();

app.UseAuthentication();

app.UseAuthorization();

app.UseApiCustomExceptionHandler();

app.MapControllers();

app.Run();

I answered this exact question recently, and got marked best answer. Here's the question link, the answer gives detailed directions as well on how to use the solution while fetching data from a service or URL.

I know my code works when I run everything on localhost but when i try deploying to heroku i have an issue

There is a bug in Chrome that has affected users for years now, it can be found here .

You can use the Chrome extension Allow-Control-Allow-Origin: * found here: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Alternatively you can use http://lacolhost.com/ which points to 127.0.0.1 like localhost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question CORS problem - Access to fetch at *** from origin *** has been blocked by CORS policy: No 'Access-Control-Allow-Origin' - PUT request to Firebase Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Access to XMLHttpRequest at localhost:3000 from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource How to fix "assess has been blocked by CORS policy: No 'Access-Control-Allow-Origin' in react How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? Javascript XMLHttpRequest - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM