I had an issue with the axios.get() when I tried to call my API from the frontend, it returned but when I test my backend with postman it is okay.
Cannot GET http://localhost:3040/v2/user/[object%20Object]
Please check code below:
backend api
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!');
}
}
);
frontend
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);
});
};
and it return result below, the API request URL should be like this http://localhost:3040/v2/user/62aec70881e46a4794b3a424
. I don’t know why it returns [object%20object]
in URL.
Please check the image error result below
2
Answers
In the posted images I can see the log for
user_id
is in this format:This means
useParams();
is returning an object with the propertyuser_id
inside it.So what you want is to extract that property.
To do that, as @osmanys-fuentes-lombá mentioned you should do somehting like:
This should assign the value direct to the
user_id
and not create an object withuser_id
as a property.To complete the answer of @Renato, variable
user_id
is an object{user_id: '62aec...'}
. When JavaScript constructs stringhttp://localhost:3040/v2/user/${user_id}
, it will internally callobject.toString()
which will result in[object Object]
, thats why you will see