我有 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 代码中遵循以下内容:
启动.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.
}
尽管如此,我还是遇到了同样的错误。
我的 Fetch 代码是:
示例.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));
}
这是一个非常常见的问题,但我仍然无法解决。请帮忙。
编辑:请建议两种类型的URL。因为我还在主服务器上部署了这个 Web API,所以从服务器 URL 访问也会出现相同的错误。http://https://
天涯尽头无女友
相关分类