c# - 即使我添加了 app.useCors (Angular, c# .net core API),也会出现 Access-Control-Allow-Origin 错误
问题描述
即使我在我的启动类中添加了 useCors,仍然会出现 Access-Control-Allow-Origin 错误。我也在使用 Angular 5。我曾经在运行我的项目时遇到此错误,但我通过在启动时添加 cors 来修复它,但现在当我尝试从我的 Angular 项目中调用 post api 方法时得到它。
我的startup.cs代码:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
解决方案
You can use proxy in your client and change client's origin to whatever you want.
The advantages of this solution are :
- You don't need to define CORS in you'r back-end ( increase security )
- You don't need to be worry about your client as well as you just run your project via npm start, as soon as you want to release your application you can run ng build command and proxy will be ignored from your setting.
For using proxy
edit
"start"
of yourpackage.json
to look below"start": "ng serve --proxy-config proxy.conf.json",
create a new file called
proxy.conf.json
in the root of the project and inside of that define your proxies like below{ "/api/*": { "target": "http://localhost:56492", "secure": "false" } }
Important thing is that you use
npm start
instead ofng serve
Now in you'r service.ts , post/get requests url instead of localhost:56492/... just type /api/Film.
Read more from here : Proxy Setup angular 2 cli
推荐阅读
- reactjs - 如何在 MUI 中设置抽屉的纸张样式?
- java - 在 Java 中关闭 ServerSocket 时,SocketException 连接被中止
- c# - ASP Razor 页面 BindProperties 值在 Post 上丢失
- javascript - 我如何在 React js 的 div 中更改我的 background_image
- angular - ngb 模态角度的 ngb 日期选择器问题
- node.js - Node.js 应用程序无法在 Heroku 上正确部署
- pytorch - 在分布式 DGL 中,如何获得网络开销?
- c# - 确定控制器类中的对象类型
- google-bigquery - Bigquery 使用两个键列删除重复行
- python - Django:¿动态加载选择字段还是创建外键模型更好?