【问题标题】:How to do a post request in ReactNative with formData如何使用表单数据在 React Native 中进行发布请求
【发布时间】:2017-09-18 09:02:10
【问题描述】:

我需要使用 fetch 进行发布请求 像这样 in Postman.

以及我尝试过的:

 let formData = new FormData();
      formData.append('username', String(username));
      formData.append('password', String(password));
  let init = {
    method: 'POST',
    header:{
      'Content-Type': 'application/x-www-form-urlencoded'
    },
   body: formData
}
  fetch(url, init)

它在 Postman 中成功,但在 fetch 中失败,返回 400 错误,没有参数。希望有帮助,谢谢

所以我改变了我的代码

 var details = {
          'username': '123',
          'password': '123',
      };
      var formBody = [];
      for (var property in details) {
      var encodedKey = encodeURIComponent(property);
      var encodedValue = encodeURIComponent(details[property]);
      formBody.push(encodedKey + "=" + encodedValue);
     }
      formBody = formBody.join("&");

      let init = {
        method: 'POST',
        header:{
          'Accept': 'application/json',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
       body: formBody
    }
      fetch(url, init)

但得到同样的错误

控制台formBody:

username=123&password=123

我的标题键错误,那是错误

应该是:

let init = {
            method: 'POST',
            headers:{
              'Accept': 'application/json',
              'Content-Type': 'application/x-www-form-urlencoded'
            },
           body: formBody
        }

而不是

let init = {
                method: 'POST',
                header:{
                  'Accept': 'application/json',
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
               body: formBody
            }

【问题讨论】:

  • 我发现我的 content-type 在请求中变成了“text/plain;charset=UTF-8”。但是我还是不知道为什么。
  • 我的头像钥匙错了。那是错。

标签: react-native fetch


【解决方案1】:

状态码 400 表示您发送了错误的请求,即服务器预期其他内容。

在这种情况下,您发送的是原始 multipart/form-data(Postman 中的第一个选项),而您说您在标题中发送 x-www-form-urlencoded

由于您要根据 Postman 屏幕截图使用后者,因此您必须以 x-www-form-urlencoded 格式发送您的正文。

【讨论】:

  • 如何在 x-www-form-urlencoded 中格式化我的正文?
  • 如何在 x-www-form-urlencoded 中发送你的身体是一个不同的问题,但你可能会找到答案here
猜你喜欢
  • 2018-07-02
  • 2018-03-19
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
相关资源
最近更新 更多