【发布时间】:2017-05-03 07:25:57
【问题描述】:
我正在学习 Angular 2。这是我应该从 ASP.NET Web api 应用程序中提取数据的服务。
@Injectable()
export class ExpenseService {
private _expUrl = "http://localhost:65400/api/expenses";
constructor(private _http: Http){}
getExpenses(): Observable<IExpense[]> {
return this._http.get(this._expUrl)
.map((response: Response) => <IExpense[]>response.json())
.do(data => console.log('ALL: ' + JSON.stringify(data)))
.catch(this.handleError)
}
//more here...
}
以上代码在 Microsoft Edge 中运行良好。但是,在 Chrome 和 FireFox 中,我收到以下错误:
XMLHttpRequest cannot load http://localhost:65400/api/expenses.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed
我已经按照许多帖子的建议在我的 web api 中启用了 CORS。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
//...
app.UseCors(builder =>
builder.WithOrigins("http://localhost:3000/"));
}
这并没有改变结果。在 Edge 工作正常时,我在 Chrome 和 FireFox 中仍然遇到同样的错误。
感谢您的帮助
【问题讨论】:
-
客户端代码完全无关,CORS必须在服务器端实现,它是浏览器决定它的可用性,而不是javascript。您的问题应该是如何在 .NET 中实现它而不是有角度的。这应该不难研究......这个网站上有数千个 CORS 问题,整个网站都致力于它以及许多其他网络资源
-
伙计们,别再投票了。我对CORS一无所知。我收到一个错误,这就是我在这里寻求帮助的原因。我应该更改标题吗?
-
是的,你应该做一些研究。每周都会提出数百个 CORS 问题
-
@charlietfl,试着表现得很好。您可以免费提供帮助。你不认为我已经对这个主题进行了研究。我发布了我在网上找到的代码。
-
显然不是...根据下面的答案,您正在寻找的内容在手册中是正确的。在这里提问应该是最后的手段,我的观点是这并不难研究
标签: angularjs asp.net-web-api asp.net-core cors