如何在授权标头中将带有 fetch 和 cors 的 JWT 令牌发送到 Express 服务器?

dan*_*ski 8 http-headers express reactjs fetch-api react-redux

我可以从 localStorage 检索 JWT 令牌并将其req.body发送到headers.Authorization. 我可以在客户端记录令牌,但不会在服务器上收到它。

客户:React、Redux-Saga。

function* getInitialStateFetch(){

  var actionType = 'GET_INITIALSTATE_REDUCER';
  var path = 'react/listings28';

  var token = localStorage.getItem('my_tkn');
  console.log(token) // logs token

  var httpHeaders;

  if(token){
  httpHeaders = { 
    'Content-Type' : 'application/x-www-form-urlencoded', 
    'Accept' : 'application/json',
    'Authorization' : `Bearer ${token}`
  };
  } else {
    httpHeaders = { 
      'Content-Type' : 'application/x-www-form-urlencoded', 
      'Accept' : 'application/json'
    };
  }

  let options = {
    method: 'GET',
    mode: 'no-cors',
    headers: new Headers(httpHeaders),
    credentials: 'same-origin'
  };

  yield call(apiCall, path, options, actionType);
}
Run Code Online (Sandbox Code Playgroud)

apiCall.js

export default function* apiCall(path, options, actionType){

  try {
    const response = yield call(fetch, `http://blah/${path}`, options);
    const data = yield call([response, response.json]);

    // call reducer
    yield put({type: actionType, payload: data});
  } catch (e) {
    console.log(e.message);
    console.log(`error api call for ${actionType}`);
  }
}
Run Code Online (Sandbox Code Playgroud)

服务器:快递。

router.get('/react/listings28', parserFalse, (req, res)=>{


  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3333');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.setHeader('Access-Control-Allow-Credentials', true);

  var token = req.headers.Authorization; // nothing here

  console.log(`req headers below`);
  console.log(req.headers); // no Authorization here
}
Run Code Online (Sandbox Code Playgroud)

来自服务器的 req.headers 截图

来自服务器的 req.headers 截图

dan*_*ski 4

终于想通了。切入正题 - 它不起作用,因为浏览器需要发送授权标头,mode: 'no-cors'但如果删除 mode: no-cors 那么 fetch() 甚至不会尝试从本地主机发送请求,但会正常工作如果我将bundle.js上传到服务器。如果你想发送cookie,你还需要将凭据设置为同源,默认情况下在 fetch() 中凭据设置为省略。

因此,解决这个问题的方法是使用 webpack 的开发代理,这样你就可以使用你的服务器而不是本地主机。