Home > Blockchain >  Cannot send object in post request
Cannot send object in post request

Time:01-06

I would like to send an object from backend to the frontend in post request. I get the object on the frontend, but there are no datas in there.

This is my function on frontend (Vue 3):

backend2(e){
      e.preventDefault();
      fetch('http://localhost:5000/enemystrongest', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({enemyCards: this.enemysCards})})
      .then((res) => {return res})
      .then((res) => {console.log(res)})
    },

And this is my backend root.js (NodeJS):

router.post('/enemystrongest', (req, res, next) => {
    let cards = req.body;
    res.setHeader("Content-Type", "application/json")
    res.send(findEnemyStrongest(cards));
});

Then i get this in dev tool/console:

Response {type: 'cors', url: 'http://localhost:5000/enemystrongest', redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:5000/enemystrongest"
[[Prototype]]: Object

Can anyone help me?

CodePudding user response:

You have to parse the body, this can be done by using: res.json() (this returns a promise)

backend2(e){
  e.preventDefault();
  fetch('http://localhost:5000/enemystrongest', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({enemyCards: this.enemysCards})})
  .then((res) => {return res.json()})
  .then((json) => {console.log(json)}) // as @jub0bs said this can be shortend as .then(console.log);
},
  •  Tags:  
  • Related