首页 > 解决方案 > 如何修复跨域请求被阻止:(原因:CORS 预检通道未成功)

问题描述

我已经使用 Web-API 调用构建了一个服务器端,以从 Angular 应用程序获取数据,我的注册页面正在获取数据,但它从未到达服务器端,以下错误不断发生:

跨域请求被阻止:同源策略不允许在http://localhost:58972/api/user/读取远程资源。(原因:CORS 预检通道未成功)。[了解更多]

跨域请求被阻止:同源策略不允许在http://localhost:58972/api/user/读取远程资源。(原因:CORS 请求没有成功)。[了解更多]

ERROR Object { headers: {…}, status: 0, statusText: "Unknown Error", url: " http://localhost:58972/api/user/ ", ok: false, name: "HttpErrorResponse", message: " http://localhost:58972/api/user/的 Http 失败响应: 0 Unknown Error", error: error }

标签: angularasp.net-web-api

解决方案


添加 config.EnableCors(); 在 WebApiConfig.cs 文件中注册方法

在角边添加“access-control-allow-origin”HttpHeader

如果您将 owin 与基于令牌的身份验证一起使用,那么

安装此 nuget 包https://www.nuget.org/packages/Microsoft.Owin.Cors/并添加 app.UseCors(CorsOptions.AllowAll); 在配置方法下的启动文件中。


推荐阅读