admin管理员组

文章数量:1279011

fetch('/auth/signup', {
      method: 'POST',
      body: this.state.user,
      headers: {
        'Content-Type': 'application/json'
      },
    })
    .then(function(response) {
      return response.json();
    })
    .then(data => {
      console.log(data);
    })

this.state.user is basically an object like {user: {name:"someone"} and my server side code simply do this

router.post('/signup', (req, res, next) => {
  console.log(req.body) // empty object
}

I think something is wrong with fetch, didn't see any data been pass in the network tab.

fetch('/auth/signup', {
      method: 'POST',
      body: this.state.user,
      headers: {
        'Content-Type': 'application/json'
      },
    })
    .then(function(response) {
      return response.json();
    })
    .then(data => {
      console.log(data);
    })

this.state.user is basically an object like {user: {name:"someone"} and my server side code simply do this

router.post('/signup', (req, res, next) => {
  console.log(req.body) // empty object
}

I think something is wrong with fetch, didn't see any data been pass in the network tab.

Share Improve this question asked Apr 22, 2017 at 3:25 Jenny MokJenny Mok 2,8049 gold badges33 silver badges62 bronze badges 4
  • Do you see a certain message in your [console] window? – Marylyn Lajato Commented Apr 22, 2017 at 3:31
  • @eeya 400 error, bad request – Jenny Mok Commented Apr 22, 2017 at 3:32
  • On your [fetch] method, what happens when you replace the url to 'signup' instead of 'auth/signup'? – Marylyn Lajato Commented Apr 22, 2017 at 3:37
  • @eeya now I manage to pass data but server return req.body as {} hmmm... – Jenny Mok Commented Apr 22, 2017 at 3:40
Add a ment  | 

1 Answer 1

Reset to default 8

Pass this.state.user to JSON.stringify() before setting at body or use FormData to POST key, value pairs. body does not expect javascript object.

body: JSON.stringify(this.state.user)

let fd = new FormData();
let {user} = this.state.user;
for (let prop in user) {
  fd.append(prop, JSON.stringify(user[prop]));
}

body: fd

本文标签: javascriptcan39t do POST to apierror 400 using fetchStack Overflow