我在redux-saga
上遇到了一些困难。我有以下传奇故事:
createPostSaga
:
function* createPostSaga(action) {
const token = yield select(selectToken);
const headerParams = {
Authorization: `JWT ${token}`
};
console.log(token, headerParams);
try {
yield call(axios.post, "/posts/", action.payload, headerParams);
yield call(getPosts());
} catch (error) {
console.log(error);
}
}
如您所见,我正在选择令牌,并将其放入具有键Authorization
和值JWT ${token}
的对象中,我的API仍在响应401 unauthorized
,但它必须是这次通话有问题,因为我可以在邮递员中复制此通话,并且一切顺利:
有人看到我做错了吗?
答案 0 :(得分:1)
尝试创建提取功能,并在.call
内使用它。
function* createPostSaga(action) {
const token = yield select(selectToken);
const headerParams = {
"Authorization": `JWT ${token}`
};
const apiCall = () => {
return axios.post('/posts', {
action.payload // only if not an object. Otherwise don't use outer {},
},
headerParams: headerParams,
).then(response => response.data)
.catch(err => {
throw err;
});
}
console.log(token, headerParams);
try {
yield call(apiCall);
yield call(getPosts());
} catch (error) {
console.log(error);
}
}
答案 1 :(得分:0)
您必须像这样调用该函数。
function* createPostSaga(action) {
const token = yield select(selectToken);
const headerParams = {
Authorization: `JWT ${token}`
};
console.log(token, headerParams);
try {
yield call(axios.post, "/posts/", action.payload, {headers:headerParams});
yield call(getPosts());
} catch (error) {
console.log(error);
}
}