如何从 Sanity 获取数据到 React?

Sev*_*ev -5 cors reactjs sanity

我无法理解如何从理智中获取数据。我已经阅读了文档,但我仍然很困惑。

我尝试将数据记录到控制台,但它给了我一个错误,例如“请求的资源上不存在‘Access-Control-Allow-Origin’标头。”

import React from "react";
import sanityClient from "@sanity/client";

const Post = () => {
  const client = sanityClient({
    projectId: "6sf5fafo",
    dataset: "production",
    useCdn: true
  });
// fetching the data
  client
    .fetch('*[__type == "post"][0]{title, "name": author->name}', {})
    .then(res => {
      console.log("Post info: ", res); // Here is when i tried to log the data but gets an error message.
    })
    .catch(err => {
      console.log(err);
    });
  return (
    <div>
      <h1>Hello</h1>
    </div>
  );
};
export default Post;
Run Code Online (Sandbox Code Playgroud)

有人可以对我的代码进行一些编辑,以正确地从理智中获取数据,我们将非常感激。

tho*_*max 5

您收到此错误是因为 Sanity 拒绝来自未知浏览器来源的访问。默认情况下(生成新项目时),唯一允许的来源是http://localhost:3333. 您可以授予对任何其他来源的访问权限。

假设您正在https://studio.mysite.com上运行 Content Studio ,并且想要授予对该 URL 的访问权限。有两种方法可以做到这一点:

  1. 打开终端,将目录切换到保存 Studio 源代码的位置,然后键入:
sanity cors add https://studio.mysite.com
Run Code Online (Sandbox Code Playgroud)
  1. 转到您的项目设置并通过 Web UI 添加源。由于您的projectId是 ,这些设置可以在https://manage.sanity.io/projects/6sf5fafo/settings/api6sf5fafo找到

有关 Sanity 和 CORS 的更多信息,请参阅https://www.sanity.io/docs/front-ends/cors上的文档