关于reactjs:Redux内axios的自定义标头问题

Custom Header problem with axios inside Redux

我正在尝试使用"自定义"标头访问登录API。首先,我收到了CORS错误:

Access to XMLHttpRequest at 'URL' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't
pass access control check: No 'Access-Control-Allow-Origin' header is
present on the requested resource

然后我通过NO CORS插件禁用了CORS。现在我得到了:

Access to XMLHttpRequest at 'URL' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't
pass access control check: It does not have HTTP ok status.

下面是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    const userDetails = { email, password };

    let data = JSON.stringify({
          request : {
                    ascUser :
                      {
                        userName :"[email protected]",
                        password :"12345678"
                      }
                    }
    })
    return dispatch => {

      axios.request('URL', {data:data},
        {headers: {
        'Content-Type': 'application/json',
        'x-transId' : '****',
        'x-channel-id' : '***'
      }}
      )
      .then(res => res.json())
      .then(res => {
        console.log(res)
          if(res.error) {
              throw(res.error);
          }
          dispatch(
            userLogin({
            ...userDetails
          })
        );
          return res.products;
      })
      .catch(error => {
        console.log(error)
      }
      )
  };
}```


您需要在后端(可能在您的nodejs服务器上)使用此https://www.npmjs.com/package/cors

  • npm i cors --save
  • 2.

    1
    2
    3
    4
    var express = require('express')
    var cors = require('cors')
    var app = express()    
    app.use(cors())