0

I want to fetch and display lists of my content on simple blog. But when I run the code, it always says that my request has been blocked by a CORS.

I'm even lost because I just want to see the data displayed.

This is my code.

import { createClient } from '../../../prismicio'
import React, { useEffect, useState } from 'react'

export default function Page() {
  const [page, setPage] = useState(null)

  useEffect(() => {
    const fetchData = async () => {
      const client = createClient()
      const uid = 'my-first-post' // Replace with your desired UID

      try {
        const response = await client.getByUID('blog_content', uid)
        setPage(response)
        console.log(response)
      } catch (error) {
        console.error('Error fetching data:', error)
      }
    }

    fetchData()
  }, [])

  return (
    <div className="mt-40">
      {page ? <h1>Page is fetched.</h1> : <p>Loading...</p>}
    </div>
  )
}

I think the code is correct, but when I check my console, it says..

from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Can anyone please help? Ask me questions and I'll respond to it.

Iroro
  • 39
  • 5
  • Do you have an 'Access-Control-Allow-Origin' header on the resource you're requesting? – Johnny John Boy Jun 22 '23 at 11:45
  • Potential duplicate https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe?rq=2 – Johnny John Boy Jun 22 '23 at 11:47
  • @JohnnyJohnBoy since I'm using nextJs, I thought I'll have the CORS enabled to run from my localhost directly? – Iroro Jun 22 '23 at 11:55
  • The error is self explanatory, you don't have an 'Access-Control-Allow-Origin' header on the resource you're requesting. You need to add one, nothing you can do to the client code. Maybe try reading this https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin – Johnny John Boy Jun 22 '23 at 12:47

1 Answers1

2

Next.js recommends fetching data from a CMS like Prismic using getStaticProps().

Assuming you are using the Pages Router, you can move your Prismic query into a getStaticProps() function. The return value of that function determines the props provided to your page component, which can be used to render your content.

Data fetched on the server (i.e. Node.js) is not subject to CORS.

import { createClient } from "@/prismicio";

export default function Page({ page }) {
  return (
    <div className="mt-40">
      {/* Do something with the `page` prop. */}
    </div>
  );
}

export async function getStaticProps({ params, previewData }) {
  const client = createClient({ previewData });

  const page = await client.getByUID("blog_content", params.uid);

  return {
    props: { page },
  };
}
Angelo Ashmore
  • 366
  • 1
  • 4
  • but for SEO, this is not really a good approach. Also, nextjs is using App router as the first choice in their docs. – Iroro Jun 25 '23 at 22:30
  • @Iroro getStaticProps is actually the preferred approach for SEO, as it prerenders your content. Fetching client-side, like the original post was, is much worse for SEO because the content only comes in once all of the JS loads. – Alex Trost Jun 26 '23 at 10:12
  • Woah! Then I must have missed out on the explanation, lol. I just checked the docs. https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-props Thanks man! – Iroro Jun 26 '23 at 10:31
  • @Iroro If you are using the App Router, you can find a querying example in the Prismic docs here: https://prismic.io/docs/fetch-data-nextjs#perform-a-query – Angelo Ashmore Jun 27 '23 at 21:05