1

I am trying to get data as given solution above but still i am getting undefined instead of data but when I send this same request through postman and thunderclient it gives me success with 200 status code. Please Guys, help me out...

export async function getServerSideProps(context) {

    const res = await fetch('http://localhost:5000/api/blogpost/view');
    const { data } = await res.json();
    return {
      props: {
          blog: data,
        },
    }
  }
const Page = ({blog}) => {
    console.log({ blog: blog, title: "nothing" });
    return (
        <div><h1>Hello</h3></div>
 )}

export default Page;

**I also have tried the fetch request inside try-catch and then also I got same undefined message **

export async function getServerSideProps(context) {
  // Fetch data from external API
  try {
    const res = await fetch('http://localhost:5000/api/blogpost/view');
    const { data } = await res.json();
  } catch (error) {
    console.log(error);
  }
  console.log(data);

  // Pass data to the page via props
  return { props: { blog: data } };
}

Console Data that I am getting is same as before

{ blog: undefined, title: 'nothing' }
Kannu Mandora
  • 479
  • 2
  • 10
hassan
  • 21
  • 3

1 Answers1

0

One possible scenario is your api do not have "data" object. Try to change "const {data}" to "const data". It would be more helpful if you send a sample response from your api.

export async function getServerSideProps(context) {

const res = await fetch(`http://localhost:5000/api/blogpost/view`);
const  data  = await res.json();
return {
  props: {
      blog: data,
    },
}
 }
const Page = ({blog}) => {
console.log({ blog: blog, title: "nothing" });
return (
    <div><h1>Hello</h3></div>
)}

export default Page;
Nani
  • 65
  • 6
  • I already have tried with this.... And it didn't work. – hassan Aug 01 '23 at 06:58
  • can you check if the API is returning CORS error? – Nani Aug 01 '23 at 07:54
  • It is not returning any cors error. Error during server side rendering only. I have tried with normal fetch API(Client Side Rendering), on the same page it gives me data. When I tried with SSR, It giving me undefined. – hassan Aug 01 '23 at 08:17
  • I am getting this error on nextjs latest version. nextjs version 12 is working fine. Can you explain what changes I need to do to get SSR in latest version of nextjs? – hassan Aug 01 '23 at 12:17