在React js中获取api post post返回403 forbidden错误,但在postman中使用相同的URL

时间:2017-08-08 19:04:13

标签: reactjs reactjs-flux

下面的代码不起作用并且返回403禁止但是相同的url给出了正确的响应postman工具。

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

4 个答案:

答案 0 :(得分:2)

您需要在请求中添加凭据:'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));

答案 1 :(得分:1)

请阅读本文Cross-Origin Resource Sharing,然后将API的“ Content-Type”更改为“ text / plain”。它将工作(获取和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));

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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