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

时间:2017-12-19 01:17:26

标签: reactjs express http-headers react-redux fetch-api

我可以从localStorage检索JWT令牌并将其发送到req.body但由于某种原因,我无法使用headers.Authorization中的fetch()将其发送到服务器。我可以在客户端记录令牌,但不能在服务器上接收令牌。

客户: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);
}

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

服务器:快递。

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
}
来自服务器的

req.headers截图

req.headers screenshot from the server

1 个答案:

答案 0 :(得分:0)

终于明白了。切入追逐 - 它将无法工作,因为浏览器发送授权标头需要mode: 'no-cors',但如果你删除模式:no-cors然后fetch()甚至不会尝试发送请求localhost但如果我将bundle.js上传到服务器,它将正常工作。如果要发送cookie,还需要将凭据设置为同源 - 默认情况下,fetch()凭据设置为省略。

所以解决这个问题的方法是使用webpack的dev代理,这样你就可以使用服务器而不是localhost。