【问题标题】:React native fetch() 403 status反应本机 fetch() 403 状态
【发布时间】:2020-05-08 06:40:48
【问题描述】:

我有一个 API 端点在邮递员中运行良好,具有以下选项

上述请求可以得到200状态并得到响应。现在我正在尝试使用 fetch 方法实现与 React Native 相同的 API。

      fetch('https://example.com/api/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx'
        },
        body: {
          "useremail": "testuser@example.com",
          "userpassword": "123456"
        },
      })
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
      }).catch((error) =>{
        console.error(error);
      });

上面的代码不起作用,我得到 403 状态。

【问题讨论】:

标签: reactjs rest react-native fetch


【解决方案1】:

你试过了吗

实现这一点的简单方法是将此属性用于您的AndroidManifest.xml,您可以在其中允许所有请求的所有http:

android:usesCleartextTraffic="true"

不要怀疑

【讨论】:

【解决方案2】:

你在传递数据而不将其转换为 json 会在这里出现问题

  fetch('https://example.com/api/user/login', {
        method: 'POST',
        credentials : 'include',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'token':'xxxxxx-xxxx-xxxx-xxxx-xxxxx',
        },
        body: JSON.stringify({ // convert object to json 
          "useremail": "testuser@example.com",
          "userpassword": "123456"
        }) ,
      })
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);
      }).catch((error) =>{
        console.error(error);
      });

【讨论】:

  • 我认为“令牌”标头不是由代码发送的
  • 我找到了问题的原因。那是因为“令牌”作为“令牌”进入服务器
  • 该问题与stackoverflow.com/questions/46200756/…有关,“令牌”被视为来自反应的“令牌”。我们要求 API 开发人员更改为接受“令牌”
【解决方案3】:

HTTP 403 是 HTTP 服务器与客户端通信的标准 HTTP 状态代码,表示由于某种原因禁止客户端访问请求的(有效)URL。服务器理解请求,但由于与客户端相关的问题而无法执行。

所以在你的邮递员的第一步使用一个假的用户密码来看看你是否再次得到 403, 如果你得到了,这意味着你在发送你的 react 原生数据时遇到了问题。

所以你应该专注于你的发送请求代码,

According to docs 你可以这样发帖

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});

确保您正确发送用户通行证,并且没有遗漏任何拼写错误

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多