I am having some difficulties with redux-saga
. I have the following 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);
}
}
As you can see I am selecting my token, and putting into an object with key Authorization
and value JWT ${token}
, my API is still responding with 401 unauthorized
, but it must be an issue with this call because I can replicate this call in Postman and it goes through fine:
Does anyone see what I did wrong?
Try to create a fetch function and use it inside .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);
}
}
You have to call the function like this.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.