NextJs 从 Prismic 获取数据受到 CORS 阻止。

huangapple go评论64阅读模式
英文:

NextJs Fetch Data from Prismic blocked by CORS

问题

我想在简单的博客上获取和显示我的内容列表。但是当我运行代码时,它总是说我的请求被CORS阻止了。

我甚至迷失了,因为我只想看到数据显示出来。

这是我的代码。

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' // 用你想要的UID替换

      try {
        const response = await client.getByUID('blog_content', uid)
        setPage(response)
        console.log(response)
      } catch (error) {
        console.error('获取数据时出错:', error)
      }
    }

    fetchData()
  }, [])

  return (
    <div className="mt-40">
      {page ? <h1>页面已获取</h1> : <p>加载中...</p>}
    </div>
  )
}

我认为代码是正确的,但当我检查控制台时,它显示了以下错误消息。

来自origin 'http://localhost:3000' 的请求已被CORS策略阻止:所请求的资源上没有'Access-Control-Allow-Origin'标头。

有人可以帮忙吗?
向我提问,我会回复的。

英文:

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 &#39;../../../prismicio&#39;
import React, { useEffect, useState } from &#39;react&#39;

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

  useEffect(() =&gt; {
    const fetchData = async () =&gt; {
      const client = createClient()
      const uid = &#39;my-first-post&#39; // Replace with your desired UID

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

    fetchData()
  }, [])

  return (
    &lt;div className=&quot;mt-40&quot;&gt;
      {page ? &lt;h1&gt;Page is fetched.&lt;/h1&gt; : &lt;p&gt;Loading...&lt;/p&gt;}
    &lt;/div&gt;
  )
}

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

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

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

答案1

得分: 2

Next.js 建议使用 getStaticProps() 从像 Prismic 这样的 CMS 获取数据

假设您正在使用 页面路由器,您可以将 Prismic 查询移到 getStaticProps() 函数中。该函数的返回值确定提供给您的页面组件的 props,可以用于呈现您的内容。

在服务器上获取的数据(即 Node.js)不受 CORS 限制。

import { createClient } from "@/prismicio";

export default function Page({ page }) {
  return (
    <div className="mt-40">
      {/* 使用 `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 },
  };
}
英文:

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 &quot;@/prismicio&quot;;

export default function Page({ page }) {
  return (
    &lt;div className=&quot;mt-40&quot;&gt;
      {/* Do something with the `page` prop. */}
    &lt;/div&gt;
  );
}

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

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

  return {
    props: { page },
  };
}

huangapple
  • 本文由 发表于 2023年6月22日 19:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定