我可以从 localStorage 检索 JWT token 并将其发送到 req.body
中,但由于某种原因,我无法使用 header 中的 fetch() 将其发送到服务器。授权
。我可以在客户端记录 token ,但不会在服务器上接收它。
客户端: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}`);
}
}
服务器:Express。
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 来自服务器的截图
最佳答案
终于明白了。切入主题 - 它不会起作用,因为浏览器要发送授权 header ,它需要有 mode: 'no-cors'
但如果你删除 mode: no-cors 然后 fetch()甚至不会尝试从本地主机发送请求,但如果我将bundle.js上传到服务器,则可以正常工作。如果你想发送cookie,你还需要将凭据设置为同源,默认情况下在 fetch() 中凭据设置为省略。
因此,解决此问题的方法是使用 webpack 的开发代理,这样您就可以使用您的服务器而不是本地主机。
关于reactjs - 如何在授权 header 中将带有 fetch 和 cors 的 JWT token 发送到 Express 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47878735/