【问题标题】:Fetch api post call returning 403 forbidden error in React js but the same URL working in postman获取 api post call 在 React js 中返回 403 禁止错误,但在邮递员中使用相同的 URL
【发布时间】:2018-01-16 11:43:48
【问题描述】:

下面的代码不起作用并返回 403 被禁止,但相同的 url 给出了正确的响应邮递员工具。

fetch('https://example.com/', {
  method: 'POST',
  headers: {'Content-Type': 'application/json', },
 body:JSON.stringify(sampledata),
}).then(result => console.log('success====:', result))
  .catch(error => console.log('error============:', error));

【问题讨论】:

  • 在 postman 中返回什么结果?
  • json 格式的成功响应,状态为 200
  • 你是如何运行代码的?您是从本地文件加载文件还是从 http 服务器检索文件?
  • @ManuRamV 你找到解决方案了吗?

标签: reactjs reactjs-flux


【解决方案1】:

可能是 CORS 问题。常规网页可以从远程服务器发送和接收数据,但它们受到同源策略的限制。像邮递员这样的扩展不是。您必须在后端配置 CORS。

【讨论】:

    【解决方案2】:

    您需要在请求中添加 credentials: 'include'

    fetch('https://example.com/', {
          credentials: 'include',
          method: 'POST',
          headers: {'Content-Type': 'application/json', },
          body: JSON.stringify(sampledata),
    
          }).then(result => console.log('success====:', result))
            .catch(error => console.log('error============:', error));
    

    【讨论】:

    • 工作就像一个魅力,我的问题真的是由于凭据包括
    【解决方案3】:

    请阅读这篇文章Cross-Origin Resource Sharing,并将您的API“Content-Type”更改为“text/plain”。它可以工作(fetch 和 axios)

    fetch('https://example.com/', {
      method: 'POST',
      headers: {'Content-Type': 'text/plain', },
     body:JSON.stringify(sampledata),
    }).then(result => console.log('success====:', result))
      .catch(error => console.log('error============:', error));

    【讨论】:

      【解决方案4】:

      这是因为 Postman 不需要遵守 access-control-allow-origin 标头。浏览器供应商从主机服务器中查找此标头。如果服务器包含ACCESS-CONTROL-ALLOW-ORIGIN: "*"Access-Control-Allow-Methods: "GET, POST, PUT, DELETE, OPTIONS" 这将告诉浏览器该资源已授予访问权限。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-25
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多