【发布时间】:2018-06-01 09:39:16
【问题描述】:
我可以从 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 来自服务器的截图
【问题讨论】:
-
删除
mode: 'no-cors'。指定mode: 'no-cors'的效果之一是它告诉您的浏览器阻止您的前端JavaScript 代码向请求中添加除Accept、Accept-Language、Content-Language或Content-Type之外的任何标头,其值为@ 987654335@、multipart/form-data或text/plain。在stackoverflow.com/questions/42506376/…查看答案 -
我尝试过不使用 no-cors。仍然没有授权,它不会发送cookie。
-
其实还是会发送 cookie 和关闭模式 no-cors 没有区别
标签: reactjs express http-headers react-redux fetch-api