我有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
响应,但它必须与该调用一个问题,因为我可以复制在邮差此调用和它去通过罚款:
有谁看到我做错了什么?
尝试创建一个取功能,并使用它里面.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);
}
}
你必须这样调用该函数。
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);
}
}