简体   繁体   English

CORS 策略已阻止从 *** 从源 *** 获取访问权限:无“访问控制允许源”

[英]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.从来源“882541222744288: //localhost:5000/admin/authenticate ”获取访问权限“ http://localhost:3000 ”已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”header 出现在请求的资源。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

My ApiManager我的 API 管理器

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:在后端 Asp.Net Core 2.2 (Startup.cs) 中,我写道:

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.我尝试了 anerco 的答案,但它对我不起作用,我找到了这篇文章,它有一个非常相似的解决方案,但添加了.SetIsOriginAllowed(origin => true)并删除了.AllowAnyOrigin()

So you should add this code to your Configure method in startup class :因此,您应该将此代码添加到启动类中的 Configure 方法中:

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.这个错误是由于政策和安全问题而发生的,但现在我建议您获取状态代码,在我的情况下是 405 错误,这意味着现在我们必须更改请求中的标头以允许所有方法和来源(不可能)但是这对我没有帮助。

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 .所以我发现我在我的应用程序中为我的 API 启用了 cookie 加密和会话(广泛的点),因此我禁用了它们并清除了浏览器 cookie。

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 .清除您的 cookie 并通过 Mod Header 扩展添加Access-Control-Allow-Origin': '*'并再次尝试检查修复。 mod header - your header (client) mod header -您的标题(客户端)

  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根据本网站: 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:如果您的服务器基于 express.js,请将这些行添加到服务器:

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 FOR NODE EXPRESS GRAPHQL RESTAPI添加此标头中间件以避免 CORS 和任何 POST 或 OPTIONS 错误

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. 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如您所说,得到确切的错误。 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();在我阅读有关此问题的Microsoft 文档(阅读您看到的第一段)之后,据说如果您想访问服务器上的资源,请使用 JavaScript (这是我试图做的),那么您必须调用app.UseCors(); BEFORE the app.UseStaticFiles();在 app.UseStaticFiles app.UseStaticFiles();之前which is typically the opposite.这通常是相反的。

My program.cs :我的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.这是问题链接,答案提供了详细说明以及如何在从服务或 URL 获取数据时使用该解决方案。

I know my code works when I run everything on localhost but when i try deploying to heroku i have an issue 我知道当我在 localhost 上运行所有内容时我的代码有效但是当我尝试部署到 heroku 时我遇到了问题

There is a bug in Chrome that has affected users for years now, it can be found here . Chrome 中存在一个影响用户多年的错误,可以在此处找到。

You can use the Chrome extension Allow-Control-Allow-Origin: * found here: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi您可以使用 Chrome 扩展 Allow-Control-Allow-Origin:* 在这里找到: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi : 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.或者,您可以使用http://lacolhost.com/指向 127.0.0.1 就像 localhost。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS 问题 - CORS 策略阻止了从 *** 获取 *** 的访问权限:无“访问控制允许来源” - 对 Z035489FF8D092741943E4A83241F5AF9 的请求 - CORS problem - Access to fetch at *** from origin *** has been blocked by CORS policy: No 'Access-Control-Allow-Origin' - PUT request to Firebase CORS 策略已阻止从原点 '' 访问 XMLHttpRequest - Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present CORS 策略阻止了对获取的访问:请求的资源上不存在“Access-Control-Allow-Origin”header - Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 获取已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 - fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 策略已阻止在 localhost:3000 访问 XMLHttpRequest - Access to XMLHttpRequest at localhost:3000 from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header CORS 策略已阻止从原点 '' 在 '' 访问 XMLHttpRequest:没有 '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 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 - localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 如何修复“评估已被 CORS 政策阻止:反应中没有‘访问控制允许来源’ - How to fix "assess has been blocked by CORS policy: No 'Access-Control-Allow-Origin' in react 如何解决“Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? - How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? Javascript XMLHttpRequest-已被CORS策略阻止:所请求的资源上不存在“ Access-Control-Allow-Origin”标头 - 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