问题描述
我有Asp .net core 3 Web API。我正在使用 Fetch 调用 POST API 之一,然后收到以下错误:
Access to fetch at 'https://localhost:44395/api/challengeresponse/Verify' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
Failed to load resource: net::ERR_Failed
所以我研究并尝试使用 Web API 代码:
Startup.cs
private readonly string AllowedOriginPolicy = "_AllowedOriginPolicy";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(AllowedOriginPolicy,builder =>
{
var corsOrigins = new String[1] { "https://localhost:44395" };
builder.WithOrigins(corsOrigins).AllowCredentials().AllowAnyHeader().AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
app.UseCors(AllowedOriginPolicy); //at the end of the method.
}
我仍然遇到相同的错误。
sample.js
async function fetchdata(){
let _data = {
OriginalData: "coordinateid",Signature: "URL",Certificate: "introduction"
}
const response = await fetch('https://localhost:44395/api/challengeresponse/Verify',{
credentials: 'include',method: "POST",body: JSON.stringify(_data),headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err));
}
编辑:请为 http://
和 https://
两种类型的 URL 提供建议。因为我也在主服务器上部署了这个web API,从服务器URL访问也出现同样的错误。
解决方法
这个网址 https://localhost:44395
在
var corsOrigins = new String[1] { "https://localhost:44395" };
它应该是客户端的 url 。应该改成这样:
var corsOrigins = new String[1] { "[client url]" };
注意:无论您使用什么客户端,请确保它在服务器上运行。