1

I'm trying to fetch the data i get to an API route in my Next.js app but it doesn't work.

Here's my code on my API route where i get the data:

import nc from "next-connect";

const jobHandler = nc();
jobHandler.get((req, res) => {
  res.status(200).send("Get a job");
});

jobHandler.post((req, res) => {
  console.log(`webhook received: ${JSON.stringify(req.body)}`); //<---- HERE is the console log
  
  req.json(req.body);
  res.sendStatus(200); //.json(req.body);
});

export default jobHandler;

and this is what i get in console.log:

enter image description here

Now when i try to fetch the these data in my client side using SWR like this:

import useSWR from "swr";

const fetcher = async () => {
  const response = await fetch(`/api/job`);
  const data = await response.json();
  console.log("PREJ TE FETCHER", data);
  return data;
};

function AsyncForm(props) {
  
  const { data, error } = useSWR("job", fetcher);

  console.log("job prej indexi", data); //<-- This is undefined

  return (
    <>
      {data ? (<p>{data}</p>) : (<p>loading...</p>)}
    </>
  );
}

export default AsyncForm;

i get undefined.

What am i doing wrong here? how to fetch that object of data which i get on my /api/job route?

Ilir
  • 488
  • 5
  • 20
  • Are you not getting an error in the browser's console? A request to `/api/job` using the GET method will return a text response. You have to use `await response.text()` to get the data from it. Or, if you want to make a POST request you need to pass the right method in the `fetch` call – juliomalves Jan 05 '22 at 19:46
  • In the browser's console im getting this error: `PREJ TE FETCHER {"error":"Method 'GET' Not Allowed"}` no matter if i use `await response.text()` or `await response.json()`, only when i use `json()` i get the same error as an object. I think i should add something into the `GET` method of my API file above then i can fetch those data to the front end. But im not good at back end at all and i dont know how to do it. – Ilir Jan 06 '22 at 20:44

0 Answers0