调用axios.get()返回Cannot GET /[object%20Object]报错排查
问题现象
- 前端通过
axios.get()调用后端用户查询接口时请求异常,同接口用Postman测试可正常返回响应 - 控制台报错信息:
Cannot GET http://localhost:3040/v2/user/[object%20Object]
- 预期合法请求URL格式为
http://localhost:3040/v2/user/62aec70881e46a4794b3a424,实际请求路径末尾被拼接为[object%20Object]
相关代码
后端接口代码
router.get( '/:user_id', userAuthorization, async (req, res) => { const _id = req.params.user_id; try { const user = await getUserById({ _id }); if (!user) { res.status(404).send('User not found!'); } res.json(user); } catch (error) { console.error(error.message); res.status(500).send('Server error!'); } } );
前端问题代码
const user_id = useParams(); useEffect(() => { loadLevels(); adminGetUserById(); }, []); const adminGetUserById = async () => { console.log('user id ---> ', user_id); await axios .get(`http://localhost:3040/v2/user/${user_id}`) .then((user) => { console.log('user res ---> ', user.data); }) .catch((error) => { console.log(error.message); }); };
问题原因
React Router的useParams() Hook返回值是包含当前路由所有匹配参数的键值对对象,不是单个参数的字符串值。
当前代码直接把整个返回对象拼接到URL路径中时,JS会自动将对象转为字符串格式[object Object],经过URL编码后就变成了请求路径里的[object%20Object],最终请求路径和后端路由规则不匹配,触发404错误。
修复方法
从useParams()的返回对象中解构出和路由参数名(后端定义的:user_id)对应的字段值,再拼接到请求URL中即可。
修复后的前端代码:
// 从useParams返回的对象中解构出user_id字段 const { user_id } = useParams(); useEffect(() => { loadLevels(); adminGetUserById(); }, []); const adminGetUserById = async () => { console.log('user id ---> ', user_id); await axios .get(`http://localhost:3040/v2/user/${user_id}`) .then((user) => { console.log('user res ---> ', user.data); }) .catch((error) => { console.log(error.message); }); };
注意:解构的字段名必须和路由定义里的参数名完全一致,如果前端路由配置中该参数命名不是user_id,需要对应调整解构的字段名。
内容的提问来源于stack exchange,提问作者Jonh
相关产品推荐
相关产品推荐

