Home > Mobile >  NEXTJS - fetching data from the server
NEXTJS - fetching data from the server

Time:11-21

I want to fetch data from the nextjs server on the front end, however the code after fetch() doesn't work in the onSubmit() function. here is the /test page

pages/test

  const onSubmit = (data) => {
    console.log("________");
    users.map(async (user, index) => {
      if (data.email === user.email) {
        if (data.password === user.password) {
          console.log("hi");

          const data = await fetch("http://localhost:3000/api/test");

          //  after the fetch, this code does not run
          console.log("back-end is: ", data);  

        }
      }
    });
  };  

and here is my code in /api/test

export default async function student_method(req, res) {
  return console.log("get in server");
}

so please what is the problem??

i'm try to get the data inside the database so we need to use fetch() method but fetch() work succesfully but code after fetch() does not work

CodePudding user response:

I think the issue is using the return statement on the server side. NextJS provides helper methods in the res object you receive in your server-side function.

Try something like this:

res.status(200).send("get in server");

For details, see here: API Routes: Response Helpers

CodePudding user response:

const data = await fetch("http://localhost:3000/api/test");

The problem is that line. There you waiting a Promise resolve, but if you see you api/test you only return a log.

Please try returning a Promise.

CodePudding user response:

The code is not working now because you're waiting for the server response but you aren't sending anything from the server.

You should send response to the client like this:

export default async function student_method(req, res) {
  /* status code 200 or any other status codes */
  res.status(200).send("get in server");
}
  • Related