reactjs - 如何从 React 发送 CORS 请求?

标签 reactjs http

我在发送 header 中带有 token 的 CORS 请求时遇到问题。 获取代码:

fetchApi() {
    fetch('http://some-link.com',
    {
        headers: {
          'Accept': 'application/json',
          'auth-token': 'xxxxxxxxx'
        },
        method: "GET"
    }).then(response => response.json())
        .then(function(response){
            this.setState({hits:response});
        }).catch(function(error) { console.log(error); });

        console.log(this.state.hits);
};

控制台日志: 访问“http://some-link.com” '来自原产地' http://localhost:3000 ' 已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段 auth-token。

网络请求日志:

General
Request URL: http://some-link.com
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: some_ip:80
Referrer Policy: no-referrer-when-downgrade

Response Headers
Access-Control-Allow-Headers: origin, x-requested-with, content-type, auth_token
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Cache-Control: no-cache, private
Connection: Keep-Alive
Content-Length: 8
Content-Type: application/json
Date: Tue, 13 Nov 2018 13:30:35 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Debian)

Request Headers
Provisional headers are shown
Access-Control-Request-Headers: auth-token
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Referer: http://localhost:3000/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

任何想法可能是错误的?

最佳答案

您必须更改服务器设置以允许 header “auth-token”。

完成此操作后,您的请求就会生效。

您目前允许“auth_token”,而不是“auth-token”。

或者,在前端更改 header 名称,如下所示:

 headers: {
   'Accept': 'application/json',
   'auth_token': 'xxxxxxxxx'
 }

关于reactjs - 如何从 React 发送 CORS 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282348/

相关文章:

javascript - 异步调用两个值更新的正确方法是什么?

javascript - 将 Babel 添加到 HTML

http - 如何将udp mpeg ts流转换为http流?

java - 编写一个简单的 HTTP 服务器来接受 GET 请求

http - 将二进制数据发布到 Scala Play Framework 网站的最佳方式

reactjs - [material-ui],[redux-from] 使用动态选项选择

javascript - 我应该使用 connect 还是 hooks 来进行 React Redux,哪个性能更好?

javascript - Next.Js 带有样式组件的 React 应用程序。警告 : Prop `className` did not match. 服务器: "x"客户端: "y"

http - http.ResponseWriter在主体中返回回车符

c# - 进行 Http 调用时套接字异常