修改说明:这个问题是关于为什么XMLHttpRequest/fetch等。在浏览器上,Postman不受相同访问策略限制(您会收到提到CORB或CORS的错误)。这个问题不是关于如何修复“No‘Access Control Allow Origin’…”错误。这是关于它们发生的原因。

请停止发布:阳光下每种语言/框架的CORS配置。而是找到相关语言/框架的问题。允许请求绕过CORS的第三方服务用于关闭各种浏览器的CORS的命令行选项


我试图通过连接RESTful API内置Flask来使用JavaScript进行授权。但是,当我发出请求时,我会收到以下错误:

XMLHttpRequest cannot load http://myApiUrl/login. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'null' is therefore not allowed access.

我知道API或远程资源必须设置标头,但当我通过Chrome扩展Postman发出请求时,为什么它会起作用?

这是请求代码:

$.ajax({
      type: 'POST',
      dataType: 'text',
      url: api,
      username: 'user',
      password: 'pass',
      crossDomain: true,
      xhrFields: {
        withCredentials: true,
      },
    })
      .done(function (data) {
        console.log('done');
      })
      .fail(function (xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
        alert(textStatus);
      });

当前回答

出于浏览器测试目的:

Windows-运行:

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

上面的命令将禁用chrome web安全性。因此,例如,如果您正在处理本地项目,并且在尝试发出请求时遇到CORS策略问题,则可以使用上述命令跳过此类错误。基本上,它将打开一个新的铬会话。

其他回答

对我来说,我遇到这个问题是因为不同的原因,远程域被添加到源,部署的应用程序工作得很好,除了一个端点我遇到了这个问题:

Origin https://mai-frontend.vercel.app is not allowed by Access-Control-Allow-Origin. Status code: 500

and

Fetch API cannot load https://sciigo.herokuapp.com/recommendations/recommendationsByUser/8f1bb29e-8ce6-4df2-b138-ffe53650dbab due to access control checks.

在更新Heroku数据库表后,我发现我的Heroku数据表并不包含本地表的所有列。

警告:使用访问控制允许来源:*会使您的API/网站易受跨站点请求伪造(CSRF)攻击。在使用此代码之前,请确保您了解风险。

如果您使用的是PHP,这很容易解决。只需在处理请求的PHP页面的开头添加以下脚本:

<?php header('Access-Control-Allow-Origin: *'); ?>

如果您使用的是Node red,则必须通过取消注释以下行,在Node red/settings.js文件中允许CORS:

// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
  origin: "*",
  methods: "GET,PUT,POST,DELETE"
},

如果您使用的是与问题相同的Flask;你必须先安装烧瓶胸衣

pip install -U flask-cors

然后在应用程序中包含Flask cors包。

from flask_cors import CORS

一个简单的应用程序如下所示:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

有关详细信息,请查看Flask文档。

因为$.ajax({type:“POST”-调用OPTIONS$.post(-调用post

两者都不同。邮递员正确地调用“POST”,但当我们调用它时,它将是“OPTIONS”。

对于C#web服务-web API

请在web.config文件的<system.webServer>标记下添加以下代码。这将起作用:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

请确保您在Ajax调用中没有犯任何错误。

jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);
    },
    error: function () {
        console.log("error");
    }
});

注意:如果您正在从第三方网站下载内容,那么这对您没有帮助。您可以尝试以下代码,但不能尝试JavaScript。

System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");

要解决此问题,请在后台使用的doGet()或doPost()函数中编写这行代码

response.setHeader(“访问控制允许来源”,“*”);

您可以键入正在访问网站的网站或API URL端点,而不是“*”,否则它将是公共的。

您得到的错误是由于CORS标准,该标准对JavaScript如何执行ajax请求设置了一些限制。

CORS标准是客户端标准,在浏览器中实现。因此,阻止调用完成并生成错误消息的是浏览器,而不是服务器。

Postman没有实现CORS限制,这就是为什么当您从Postman发出相同的呼叫时,不会看到相同的错误。

邮差为什么不实施CORS?CORS定义了与发起请求的页面的源(URL域)相关的限制。但在Postman中,请求并非来自具有URL的页面,因此CORS不适用。