Issue
i’m new in angular and node js
i have a multitab form in angular that in one tab i want to insert record with node js to mysql table
in html form i have this:
<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>
in ts file i have below:
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)}
);
and my js file is:
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();
})
i recive error in nodejs:
**Cannot read property ‘caption’ of undefined
and dont return value of caption
adding that body_parser definition has massage :’bodyParser’ is deprecated.
and bodyParser shown with Strikethrough:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
Solution
Instead of ‘req.body.params.caption’ use ‘req.body.caption’ in the api call and check. In angular end change ‘this.http.post("localhost:3000/item_create",caption)’ to ‘this.http.post("localhost:3000/item_create",{caption})’.