Angular 2+ POST请求报错:500内部服务器错误(localhost:3000/api/pups/)
问题分析与修复方案
嘿,我瞅了下你的代码和错误情况,问题其实挺明显的😉
核心错误原因
你在Service.ts里犯了一个小疏忽:
const body = JSON.stringify(newPup.data);
但你从Component.ts传入的newPup是直接包含name、age、breed的对象,根本没有data属性!这就导致newPup.data的值是undefined,转成JSON后就变成了字符串"undefined",后端自然无法识别这种格式的请求体,这就是你报错的根源。
分步修复
1. 修正服务端请求体序列化
修改Service.ts的createPup方法,直接序列化传入的完整对象:
createPup(newPup) { const headers = new Headers({ 'Content-Type': 'application/json' }); const options = new RequestOptions({ headers: headers }); // 移除多余的.data,直接序列化newPup const body = JSON.stringify(newPup); return this.http .post(this._url, body, options) .map((res: Response) => res.json() ); }
2. 调整页面导航时机
另外你的Component.ts里还有个体验问题:this.router.navigate(['/pups'])写在了订阅逻辑外面,这会导致不管创建请求成功还是失败,页面都会立刻跳转。应该把导航逻辑移到成功回调里,确保只有数据创建成功后才跳转:
createPup() { const newPup = { name: this.name, age: this.age, breed: this.breed }; this.__pupService.createPup(newPup).subscribe( data => { console.log(data); // 成功创建后再跳转到列表页 this.router.navigate(['/pups']); }, error => { console.error('Error Adding Pup!'); console.log(newPup); return Observable.throw(error); } ); }
做完这两处修改,应该就能正常提交JSON数据给Web服务啦!
内容的提问来源于stack exchange,提问作者Souhail Ben Ali
相关产品推荐
相关产品推荐

