在我的Angular项目中,当调用Web API时,预检请求的响应具有无效的HTTP状态码404。
在我的Angular项目中,当调用Web API时,预检请求的响应具有无效的HTTP状态码404。
我知道这是CORS问题。我已经在Web API服务器端启用了CORS。GET方法正常工作,但在处理POST方法时遇到问题。请有人给我一个非常简单的Web API和客户端POST示例,并解释如何处理预检请求(preflight)、OPTIONS等等。
控制台:
1)zone.js:2935 OPTIONS http://localhost:49975/api/Add_Client_/postgoals 404 (Not Found)
2)Failed to load http://localhost:49975/api/Add_Client_/postgoals: Response for preflight has invalid HTTP status code 404.
web.config:
Angular POST方法:
save_Goals(){ let headers : Headers= new Headers(); //headers.append('Content-Type','application/x-www-form-urlencoded'); //headers.append("Access-Control-Allow-Origin","true"); headers.append('Content-Type', 'application/json'); headers.append('Access-Control-Allow-Origin','*'); headers.append('Access-Control-Allow-Methods','GET,PUT,POST,DELETE'); headers.append('Access-Control-Allow-Headers','Content-Type'); let options = new RequestOptions({ headers: headers }); return this._http.post('http://localhost:49975/api/Add_Client_/postgoals', {goal:'foo'},options) .map(res => res.json()); }
谢谢!
问题出现的原因是在使用 Angular 项目调用 Web API 时,出现了 "Response for preflight has invalid http status code 404" 的错误。这个错误通常是由于跨域请求引起的。
解决这个问题的方法是使用一个 Chrome 插件,叫做 Moesif Origin & CORS Changer。可以在 Chrome Web Store 中找到该插件。安装并启用该插件后,可以设置请求头的内容类型为 "application/x-www-form-urlencoded"。同时,在 Angular 项目中的请求头中添加以下内容:
import { HttpHeaders } from '@angular/common/http'; let headers = new HttpHeaders(); headers = headers.set('Content-Type', 'application/x-www-form-urlencoded'); headers.append('Access-Control-Allow-Origin','*'); headers.append('Access-Control-Allow-Methods','GET,PUT,POST,DELETE'); headers.append('Access-Control-Allow-Headers','Content-Type');
这样就可以解决 "Response for preflight has invalid http status code 404" 错误。
问题的出现原因是:
在使用Angular项目消费Web API时,出现了"Response for preflight has invalid http status code 404"的错误。这通常是由于跨域请求引起的,即前端请求的域与后端API的域不一致。
解决方法如下:
1. 在Angular项目中,通过HTTP头向请求中传递数据。可以使用两种方式将数据传递到HTTP头中:
Option 1:
const httpOptions = { headers: new HttpHeaders({ 'Authorization': 'my-auth-token', 'ID': emp.UserID, }) }; return this.http.post(this.url + 'testMethod', body, httpOptions);
Option 2:
let httpHeaders = new HttpHeaders(); httpHeaders = httpHeaders.append('Authorization', 'my-auth-token'); httpHeaders = httpHeaders.append('ID', '001'); httpHeaders.set('Content-Type', 'application/json'); let options = {headers:httpHeaders}; return this.http.post(this.url + 'testMethod', body, options);
2. 在后端/Web API端进行更改:
添加一个新的WebApiConfig文件,并添加以下内容:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "ID", methods: "*") { SupportsCredentials = true }); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
在Global.asax.cs文件中添加以下事件:
protected void Application_BeginRequest() { if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "ID"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200"); HttpContext.Current.Response.End(); } }
在Web API端使用以下语句获取传递的ID:
if (Request.Headers.Contains("ID")) { var ID = Request.Headers.GetValues("ID").First(); }
通过以上步骤,可以解决以下错误:
- "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access."
- "Response for preflight does not have HTTP ok status."
通过以上方法,我成功地将ID传递到HTTP头中,并在Web API端进行了获取。祝编码愉快!