Angular POST传参至Node.js报错 无法读取未定义的caption属性
Angular+Node.js联调插入MySQL数据的问题排查与修复
实现场景
作为Angular与Node.js开发初学者,你目前开发了带多标签页的Angular表单,目标是在其中一个标签页通过Node.js接口将表单记录写入MySQL表,现有各端实现代码如下:
前端HTML表单代码
<mat-card-content fxLayout="column" [formGroup]="formGroupCaption" > <mat-form-field> <input matInput placeholder="caption" formControlName="caption" autocomplete="off"> <span *ngIf="!formGroupCaption.get('caption').valid && formGroupCaption.get('caption').touched">insert caption</span> </mat-form-field> </mat-card-content> <mat-card-actions > <button mat-raised-button color="primary" type="submit" (click)="insert_caption()">Login</button> </mat-card-actions>
前端对应TypeScript逻辑代码
ngOnInit(): void { this.get_data(); this.Create_Form_Caption(); } Create_Form_Caption(){ this.formGroupCaption = new FormGroup({ 'caption': new FormControl(null, [Validators.required]) }) } insert_caption(){ const caption = this.formGroupCaption.value.caption; console.log(caption); this.http.post("http://localhost:3000/item_create", caption).subscribe( (res) => {console.log(res)} ); }
Node.js后端接口代码
app.post("/item_create", (req, res) => { console.log('caption is :' + req.body.params.caption); const insertquery = "INSERT INTO captiontbl (description) VALUES ('" + req.body.params.caption + "')"; ConnectToDB().query(insertquery, (err, result) => { if (err) { console.log("error" + err); res.sendStatus(500); return; } res.send("inserted" + result); res.end(); }) })
现存问题
- Node.js端运行时报错
Cannot read property 'caption' of undefined,无法获取前端传递的caption值 - 配置请求体解析逻辑时,编辑器提示
'bodyParser' is deprecated,导入的bodyParser字段显示带删除线,现有配置代码为:app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json());
根因与修复方案
接口取值报错修复
- 核心问题是前后端传递参数的结构不匹配:前端POST请求时直接将caption字符串作为请求体发送,最终请求体是纯字符串值,不存在
params嵌套层级;但后端代码读取的是req.body.params.caption,尝试在请求体中读取params对象时自然会触发undefined属性读取的报错。 - 额外风险:原有SQL语句直接拼接用户传入的字符串,存在SQL注入隐患,需要改用预编译占位的写法。
对应调整:
- 前端发送请求时,将参数封装为后端预期的结构:
insert_caption(){ const caption = this.formGroupCaption.value.caption; // 匹配后端读取结构,封装为带params层级的对象 const requestPayload = { params: { caption: caption } } this.http.post("http://localhost:3000/item_create", requestPayload).subscribe( (res) => {console.log(res)} ); } - 后端接口替换字符串拼接SQL的写法,改用预编译参数:
app.post("/item_create", (req, res) => { const captionValue = req.body.params.caption; console.log('caption is :' + captionValue); // 使用?作为参数占位符,传入参数数组执行查询 const insertquery = "INSERT INTO captiontbl (description) VALUES (?)"; ConnectToDB().query(insertquery, [captionValue], (err, result) => { if (err) { console.log("error" + err); res.sendStatus(500); return; } res.send("inserted" + result); }) })
bodyParser废弃提示修复
从Express 4.16.0版本开始,原有第三方bodyParser模块的核心请求体解析能力已经被整合进Express内置方法中,无需单独引入body-parser依赖,直接替换原有配置即可消除废弃提示:
// 替代原bodyParser.urlencoded的配置 app.use(express.urlencoded({ extended: true })); // 替代原bodyParser.json的配置 app.use(express.json());
注意:请求解析中间件的注册位置必须在所有业务接口路由之前,否则请求体无法被正确解析
内容的提问来源于stack exchange,提问作者mahdi.gh
相关产品推荐
相关产品推荐

