Angular 2/4 POST请求报415错误,Postman可正常调用Web API
解决Angular 4 POST请求415 Unsupported Media Type问题
我来帮你排查一下这个问题,你遇到的415错误主要是两个核心原因导致的,咱们一步步来修正:
问题1:请求头没有正确传递
你在代码里定义了带Content-Type: application/json的headers,但在调用_http.post时,并没有把这个配置传进去!反而传了一个包含params的新对象,这就导致浏览器默认用text/plain发送请求,Web API自然不支持这个媒体类型。
问题2:请求体的JSON结构错误
你用JSON.stringify([{ stock }])把数据转成了JSON,这样生成的结构是[{"stock": {...}}]——你的stock对象被包在了一个额外的stock属性里,但Web API期望的是直接包含schid、itemid等字段的对象数组,所以后端无法解析。
修正后的代码
1. service.ts 文件
CatchStockDetail(stock: any): Observable<IStockdetails[]> { // 要查看stock的具体内容,用JSON.stringify转成字符串 alert(JSON.stringify(stock)); // 直接把stock放进数组,不要额外嵌套{stock} let stockdetail = JSON.stringify([stock]); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); // 这里要传递定义好的options,而不是自定义params对象 return this._http.post('http://localhost:1234/api/NewStockCount/Stock', stockdetail, options) .map((response: Response) => <IStockdetails[]>response.json()) // 确保handleError能正确绑定this,用箭头函数或者bind .catch(error => this.handleError(error)); }
2. component.ts 文件
this._enqService.CatchStockDetail(this.stock) .subscribe(stockDetails => { // 如果是要把返回的接口数据加入数组,用扩展运算符更简洁 this.stockdetail.push(...stockDetails); // 如果只是要把当前的this.stock加入,直接写this.stockdetail.push(this.stock)即可 }, error => { console.error(error); this.statusMessage = "Problem with the service.Please try again after sometime"; });
3. Web API 代码优化
注意你定义的模型类是spGetNewStockCountDetails,但接口参数用的是List<spGetNewStockCountDetails_Result>,这两个类的结构要完全一致,否则后端也无法解析。建议统一成一个类:
[HttpPost] public void Stock([FromBody] List<spGetNewStockCountDetails> jsonvalues) { foreach (spGetNewStockCountDetails Datastock in jsonvalues) { enqentities.spGetNewStockCountDetails( Datastock.schid, Datastock.itemid, Datastock.itemcode, Datastock.itemdescription, Datastock.packingtypeid, Datastock.count ); } } // 确保这个类的属性和前端传递的JSON字段完全匹配 public class spGetNewStockCountDetails { public int schid { get; set; } public int itemid { get; set; } public string itemcode { get; set; } public string itemdescription { get; set; } public int packingtypeid { get; set; } public int count { get; set; } }
额外说明
- 你点击alert显示
[object Object]是正常现象,因为alert会把对象直接转成字符串,要查看具体内容必须用JSON.stringify(stock)。 - 修正后,Angular会正确发送
Content-Type: application/json的请求,同时请求体结构也和后端期望的一致,415错误应该就能解决了。
内容的提问来源于stack exchange,提问作者user9495407
相关产品推荐
相关产品推荐

