Rijo Rijo - 22 days ago 8
Javascript Question

Angular 4 and Nodejs http post request implementation error

I created small test application using Angular 4 and Nodejs. I want to insert a text field value to the database either Mongo or mysql.

Following files I created server.js for running nodejs, Created server>router folder with another file api.js and Angular 4 user component created.
What i did code shown below

user.component.html

<form (submit)="addHobby(hobbies,hobby.value)">
<input type="text" #hobby>
<input type="submit" value="Submit">
</form>


user.component.ts

addHobby(arrHob,hobby) {
if(arrHob.indexOf(hobby) == -1) {
this.hobbies.unshift(hobby);
this.dataService.postHobby(hobby).subscribe((posts) => {
console.log(posts);
})
}
return false;
}


Services folder contain data.service.ts

postHobby(hobby) {
return this.http.post('/api/insertHobby',hobby).map(res => res.json().data);
}


server router folder contain api.js

router.post('/insertHobby', (req, res) => {
console.log("Welcome to post method");
console.log(req.body.data);
})


When form submitting i'm getting output as only welcome to post method

req.body.data i'm getting as
*'Undefined'*
How to resolve this issue. Any way thanks to everyone..

Answer Source

since you are not passing the variable as object , you need to pass it in object format as below :

postHobby(hobby) {
return this.http.post('/api/insertHobby',{hobby: hobby}).map(res => res.json().data);
}