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

this is my code:fetch('http:localhost:3000', {method: 'POST',headers: {'Con

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.

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.

Share Improve this question asked Jun 5, 2021 at 19:51 programming_for_funprogramming_for_fun 1091 gold badge3 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

res is the Response, 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)
  });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744268974a4566005.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信