即使我在启动类中添加了
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();
}
}
您可以在客户端中使用代理并将客户端的来源更改为您想要的任何内容。
该解决方案的优点是:
对于使用代理
编辑
"start"
的 package.json
以查看下面
"start": "ng serve --proxy-config proxy.conf.json",
在项目的根目录中创建一个名为
proxy.conf.json
的新文件,并在其中定义您的代理,如下所示
{
"/api/*": {
"target": "http://localhost:56492",
"secure": "false"
}
}
重要的是你使用
npm start
而不是 ng serve
现在在你的 service.ts 中,post/get 请求 url 而不是 localhost:56492/... 只需键入 /api/Film。
从这里阅读更多内容:代理设置 Angular 2 cli