简体   繁体   中英

How do I POST a x-www-form-urlencoded request using Fetch AND work with the answer?

this is my code:

fetch('http://localhost:3000', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({
    'size': 'size_id',
    'style': 'style_id',
    'qty': '1'
  })
})
  .then(res => {
    console.log(res)
  });

My problem is that I just get 'Promise pending' returned. Im totaly new to fetch and really new to js, so please dont blame me.

res is theResponse , not the response data.

Are you expecting json? Then do:

fetch('http://localhost:3000', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({
    'size': 'size_id',
    'style': 'style_id',
    'qty': '1'
  })
})
  .then(res => res.json())
  .then(res => {
    console.log(res)
  });

otherwise get the plain response data/text like this:

fetch('http://localhost:3000', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({
    'size': 'size_id',
    'style': 'style_id',
    'qty': '1'
  })
})
  .then(res => res.text())
  .then(res => {
    console.log(res)
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM