skip to Main Content

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

https://i.stack.imgur.com/Zrmqd.png

https://i.stack.imgur.com/Ka2gf.png

2

Answers


  1. In the posted images I can see the log for user_id is in this format:

    { user_id: 'your id' }
    

    This means useParams(); is returning an object with the property user_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:

    const { user_id } = useParams();
    

    This should assign the value direct to the user_id and not create an object with user_id as a property.

    Login or Signup to reply.
  2. To complete the answer of @Renato, variable user_id is an object {user_id: '62aec...'}. When JavaScript constructs string http://localhost:3040/v2/user/${user_id}, it will internally call object.toString() which will result in [object Object], thats why you will see

    Cannot GET http://localhost:3040/v2/user/%5Bobject%20Object%5D

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search