如何使用 Fetch 发布 x-www-form-urlencoded 请求并使用答案?

问题描述

这是我的代码

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)
  });

我的问题是,我只是得到了“未决承诺”的返回。 我是 fetch 的新手,也是 js 的新手,所以请不要怪我。

解决方法

resResponse,而不是响应数据。

你期待 json 吗?然后做:

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)
  });

否则会像这样获取纯响应数据/文本:

fetch('http://localhost:3000','qty': '1'
  })
})
  .then(res => res.text())
  .then(res => {
    console.log(res)
  });