skip to Main Content
    //controller    
    const getList = asyncHandler(async (req, res) => {
          const { userId, name } = req.body;
        
          if (!userId || !name) {
            res.status(400).json({ error: 'Please enter name and userID' });
            return;
          }
        
          try {
            const user = await User.findById(userId).populate({
              path: 'lists',
              populate: { path: 'books', select: 'title author coverImage' },
            });
        
            const userList = user.lists.find((list) => list.listName === name);
        
            if (!userList) {
              res.status(400).json({ error: 'List does not exist' });
              return;
            }
        
            res.json(userList);
          } catch (err) {
            console.log(err);
            res.status(400);
          }
        });

//client
const user = JSON.parse(localStorage.getItem('user'));
  const userName = user.name;
  const userId = user._id;
  const API_URL = 'http://localhost:8080/api/lists/get-list';
  const [list, setList] = useState();
  const name = 'Currently Reading';

  useEffect(() => {
    const getCurrent = async (userId, name) => {
      const listReq = { userId, name };
      console.log(listReq);
      try {
        const response = await axios.get(API_URL, listReq);
        return response.data;
      } catch (error) {
        console.log(error);
      }
    };
    getCurrent(userId, name);
  }, []);

The http get request on postman using x-www-form-urlencoded works fine. I supply the userId and name of user. However it is failing on my client. I get the "Please enter name and userID error" If I log the list req to the console I see the right parameters. BUt the request is failing.

2

Answers


  1. await axios.get(API_URL, { params: listReq })
    

    axios.get(url[, config]),axios.post(url[, data[, config]]), get and post has different signature

    Login or Signup to reply.
  2. In a typical RESTful API, the GET method is primarily used for retrieving data from the server. However, according to the HTTP specification, the body of a GET request should be empty. Therefore, including a request body in a GET request is not considered standard practice.

    If you need to send data to the server for a retrieval operation, it’s recommended to use query parameters or path parameters instead. Query parameters are appended to the URL, while path parameters are included in the URL path itself.

    ex. http://localhost:8080/api/lists/get-list/userId/name

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