【问题标题】:fetch POST not reading sent request from react native properly获取 POST 未正确读取来自 React Native 的已发送请求
【发布时间】:2018-09-30 23:16:51
【问题描述】:

我不确定这里的实际问题是什么,可能是 API、react native 上的 fetch 实现或我的格式。

我尝试了很多不同的格式,甚至将请求硬编码到我的应用程序中,但我请求的服务器 API 仍然返回 Error 400: Bad Request 和一个显示 unsupported_grant_type 的 JSON 文件。 这是我要发送的内容的 sn-p:

var options = {
  "method": "POST",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
     "Authorization": "Basic TWVtYmVyQ2VudGVyTGFuZGluZzp0ZXN0cGFzcw==",
   },
   "data": {
     "grant_type": "password",
     "username": "MemberCenterLanding",
     "password": "testpass"
   }
}

然后我根据 API 文档使用fetch(url, options).then(response => { return response.json()... 和暂存网址http://10.64.2.149:8081/oauth/token 发送了这个。

我用邮递员尝试了这个请求,它有效,只是不是来自我的程序:( 我也尝试使用JSON.stringify()FormData 更改正文的格式,但没有任何效果。

添加:我还尝试使用 node-fetch 创建要在 node.js 上运行的迷你请求文件,但仍然无法正常工作并产生相同的结果。有趣的是,node-request 工作正常。

谁能帮我缩小这里的问题范围? react native 的 fetch() 实现是否有任何改变,可能与 API 的实现方式有关?

提前致谢!

【问题讨论】:

    标签: javascript post react-native fetch fetch-api


    【解决方案1】:

    使用body 代替数据。并使用 JSON.stringify 将 JavaScript 值转换为 JSON 字符串。

    var options = {
      "method": "POST",
      "headers": {
        "Content-Type": "application/x-www-form-urlencoded",
         "Authorization": "Basic TWVtYmVyQ2VudGVyTGFuZGluZzp0ZXN0cGFzcw==",
       },
       "body": JSON.stringify ({
         "grant_type": "password",
         "username": "MemberCenterLanding",
         "password": "testpass"
       }),
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 2018-05-26
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 2018-03-05
      • 2015-12-22
      相关资源
      最近更新 更多