Redux-Saga 将 headers 传递给 axios.post 调用
Redux-Saga pass headers to axios.post call
我在使用 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}
放入 object,我的 API 仍在响应 401 unauthorized
,但这一定是这个调用的问题,因为我可以在 Postman 中复制这个调用并且它通过得很好:
有人看到我做错了什么吗?
尝试创建一个 fetch 函数并在 .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);
}
}
我在使用 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}
放入 object,我的 API 仍在响应 401 unauthorized
,但这一定是这个调用的问题,因为我可以在 Postman 中复制这个调用并且它通过得很好:
有人看到我做错了什么吗?
尝试创建一个 fetch 函数并在 .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);
}
}