0

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..

8
  • what is "hobby" ? is it object ? , if not pass it like { hobby } in the body Commented Sep 26, 2017 at 1:07
  • 'hobby' is the text field value. I passed object format but i didn't get result Commented Sep 26, 2017 at 1:11
  • sorry typo it should be { hobby : hobby } Commented Sep 26, 2017 at 1:13
  • Okay i'm getting the result. i re write api.js as console.log(req.body.hobby); Thanks Commented Sep 26, 2017 at 1:16
  • I will put this answer , please accept the answer Commented Sep 26, 2017 at 1:21

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Here i have 1 text field only, if i have more than 10 fields i have to pass this format only?
yes , hence preferred way is to pass it as an JSON object .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.