// postman // react 应用
对于我的 react 应用程序,在调度 apiPostRequest() 时,即使用户已通过身份验证并且 token 存储在本地存储中,当它命中 API POST 请求中间件时,我也会收到 401 未经授权的错误。令人困惑的部分是我的 GET 和 DELETE api 请求工作得很好。所以我无法弄清楚为什么 POST api 返回 401 未经授权的错误?它在 postman 中运行良好。任何帮助将不胜感激。
//Accept request action
export const acceptRequest = (requestId) => ({
type : ACCEPT_REQUEST,
payload: requestId
});
// Accept request middleware
export const acceptRequestFlow = ({dispatch, getState}) => next => action => {
next(action);
if(action.type === ACCEPT_REQUEST){
const acceptRequestId = action.payload
console.log(acceptRequestId)
const URL = `/api/userConnections/acceptRequest/${action.payload}`;
dispatch(apiPostRequest(URL, setAuthorizationHeader(getState), acceptRequestId, ACCEPT_REQUEST_SUCCESS, ACCEPT_REQUEST_ERROR));
}
};
//API POST, DELETE, GET request actions
export const apiPostRequest = (url, config, body, onSuccess, onError) => ({
type: POST_API_REQUEST,
meta: {url, config, body, onSuccess, onError}
});
export const apiDeleteRequest = (url, config, id, onSuccess, onError) => ({
type: DELETE_API_REQUEST,
meta: {url, config, id, onSuccess, onError}
});
export const apiGetRequest = (url, config, onSuccess, onError) => ({
type: GET_API_REQUEST,
meta: {url, config, onSuccess, onError}
});
//API POST, DELETE, GET request middleware
export const api = ({dispatch}) => next => action => {
if(action.type === POST_API_REQUEST) {
const {url, config, body, onSuccess, onError} = action.meta;
axios.post(url, config)
.then((data) => {dispatch({ type: onSuccess, payload: body})})
.catch(error => dispatch({ type: onError, payload: error }))
}
if(action.type === GET_API_REQUEST) {
const {url, config, onSuccess, onError } = action.meta;
axios.get(url, config)
.then((data) => {dispatch({ type: onSuccess, payload: data})})
.catch(error => dispatch({ type: onError, payload: error }))
}
if(action.type === DELETE_API_REQUEST) {
const {url, config, id, onSuccess, onError } = action.meta;
axios.delete(url, config)
.then((data) => { dispatch({ type: onSuccess, payload: id })})
.catch(error => dispatch({ type: onError, payload: error }))
}
return next(action)
};
//Setting Auth Header
export const setAuthorizationHeader = (getState) =>{
const token = getState().auth.token;
const config = {
headers:{
"Content-Type": "application/json"
}
}
if(token){
config.headers['Authorization'] = token;
}
return config;
};
最佳答案
问题是您错误地使用了 post 方法。
从 axios doc 截取的图片可以看出,发帖时不指定参数名,那么传入的第二个参数就被认为是数据。
所以试试:axios.post(url, {}, config)
关于javascript - react 和 Redux : 401 Unauthorized Error POST API Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65238440/