获取 api post 调用在 React js 中返回 403 禁止错误,但在邮递员中工作的 URL 相同

IT技术 reactjs reactjs-flux
2021-05-23 12:23:34

下面的代码不起作用并返回 403 forbidden 但相同的 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));
4个回答

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

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

请阅读这篇文章跨域资源共享,并将您的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));

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