skip to Main Content

I’m using react to send date to server but there is an error

{message: ‘Invalid date format. Date should be in the format YYYY-MM-DD.’, field: ‘from’}

I’m completely sure the data is valid and here is the code

   const handleFilter = async (e) => {
    e.preventDefault();
    console.log(fromDate);
    console.log(toDate);
    try {
      const date = {
        from: dayjs(fromDate).format("YYYY-MM-DD"),
        to: dayjs(toDate).format("YYYY-MM-DD"),
      };
      console.log(date);
      const res = await newRequest.get("/analysis", date);
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

and there is the console

enter image description here

I’m tried a lot of answers like
JSON.stringify(date);
before sending
nothing work !!!

there is the postman and it’s work fine in postman
enter image description here

2

Answers


  1. are you sure your server is expecting this format ?

    try simply using fromdate.format("YYYY-MM-DD")

    or use can use moment()

    but first import it

    Login or Signup to reply.
  2. The params you’re sending through the GET request by Postman are called "body" in the Postman nav bar. But doing a GET request, you could’nt use "body" like you usually do when you’re doing a POST request.

    When you’re doing a GET request you should to pass the params instead body whitin the second param of "newRequest.get" method.
    Wich will be on the request query params:

    "https://resturant.asusapps.com/api/v1/analysis?from=2024-02-01&to=2024-03-30"
    

    Then, once "newRequest" is an Axios instance, you should do like this:

    const res = await newRequest.get("/analysis", {
        params: {
            from: date.from,
            to: date.to
        }
    });
    

    Your code will be like this:

    const handleFilter = async (e) => {
        e.preventDefault();
    
        console.log(fromDate);
        console.log(toDate);
    
        try {
            const date = {
                from: dayjs(fromDate).format("YYYY-MM-DD"),
                to: dayjs(toDate).format("YYYY-MM-DD"),
            };
    
            console.log(date);
            const res = await newRequest.get("/analysis", {
                params: {...date} 
            });
            console.log(res);
    
        } catch (error) {
            console.log(error);
        }
    };
    

    Hope this helps

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