angular - 为什么调用 API 时出现 CORS 错误
问题描述
我Angular
在前端使用,C#
作为我的后端,当我尝试编辑字段并保存它时出现此错误:
Access to XMLHttpRequest at 'http://192.168.220.14:81/api/registry' from origin 'http://artc.tj' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
PUT http://192.168.220.14:81/api/reg polyfills-es2015.23e79c711e3c227d781f.js:1 PUT http://192.168.220.14:81/api/registry net::ERR_FAILED
启动.cs:
public void ConfigureServices(IServiceCollection services)
{
//CORS
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost",
"http://localhost:4200",
"http://artc.tj",
"http://192.168.220.14")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
}
解决方案
确保Cors()
在你的Configure
方法中使用。
启动.cs
public class Startup
{
//...
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
});
});
//...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseCors(MyAllowSpecificOrigins);
//...
}
//...
}
PS 还要确保包含withCredentials: false
在您的客户请求中httpOptions
推荐阅读
- apache - 图片忽略 .htaccess 中的缓存控制
- java - 将数据从高到低排序并应用到RecyclerView
- acumatica - Segmented Key Subaccount of PrepaymentSubID do not exist in the system
- ios - 使用交叉下载管理器 - 但是,我找不到文件
- android - 我的 Live vlc 视频流可以在模拟器上运行,但不能在真实设备上运行
- ios - Swift Firebase - 获取多个 uid,然后将这些 uid 添加到孩子
- python - Why does my python code run as expected in the debugger but not otherwise?
- javascript - 博览会初始化
抛出 npm 错误(Windows 操作系统) - powershell - Powershell每行替换一次文本
- php - MySQL SELECT from table where row = (SELECT val1, val2, val3, ... etc.)