修改说明:这个问题是关于为什么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);
});
因为$.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");
通过在全球范围内应用此中间件,它对我很有用:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next) {
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', "Accept,authorization,Authorization, Content-Type");
}
}