API在Postman正常运行,React中Axios调用返回404错误求助
问题描述
我用Postman调用某API可正常运行,但使用Axios调用时返回404 Not Found,调用的URL和Postman里完全一致。Axios调用代码如下:
export const getAccountBalance = (id) => async (dispatch, getState) => { try { dispatch({ type: BALANCE_FETCH_REQUEST, }); const { userLogin: { userInfo }, } = getState(); const config = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${userInfo.token}`, }, }; const { data } = await axios.get(`getAccountByAccountNo?accountNo=${id}`,config); console.log(data); dispatch({ type: BALANCE_FETCH_SUCCESS, payload: data, }); } catch (error) { dispatch({ type: BALANCE_FETCH_FAIL, payload: error.response && error.response.data.message ? error.response.data.message : error.message, }); } };
排查与解决方案
补全完整API地址
Postman中的请求是包含服务器域名/IP的完整URL,但你的Axios代码只写了接口路径,若未全局配置Axios的baseURL,请求会发送到当前前端页面的域名下,导致404。解决方法二选一:- 直接在请求中写完整URL:
const { data } = await axios.get(`https://你的API服务器地址/getAccountByAccountNo?accountNo=${id}`, config); - 全局配置Axios的基础地址:
axios.defaults.baseURL = 'https://你的API服务器地址';
- 直接在请求中写完整URL:
验证参数传递正确性
在Axios请求前打印完整URL,确认id是否正确传递:
const requestUrl = `getAccountByAccountNo?accountNo=${id}`; console.log('实际请求URL:', requestUrl);
对比Postman中的参数值,确保id不为空或格式错误。
核对URL路径大小写
部分服务器对路径大小写敏感,仔细对比Postman和代码中的接口路径,确保大小写完全一致(比如GetAccountByAccountNo和getAccountByAccountNo会被视为不同路径)。匹配请求头信息
打开浏览器开发者工具的Network面板,查看Axios发送的请求头,和Postman中的请求头逐一对比,确认是否有缺失或不一致的字段(比如Host、User-Agent等),必要时在Axios的config中补全对应字段。
内容的提问来源于stack exchange,提问作者Debajyoti Bhattacharjee
相关产品推荐
相关产品推荐

