reactjs - How to fetch data from Sanity to React?
问题描述
I have trouble understanding on how to fetch my data from sanity. I have read the documentation but still i'm confused.
I tried just logging the data to the console but it gives me an error like, "No 'Access-Control-Allow-Origin' header is present on the requested resource."
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;
Can someone do some edits to my code to properly fetch the data from sanity it would be very much appreciated.
解决方案
You're getting this error because Sanity denies access from unknown browser origins. By default (when generating a new project), the only origin allowed is http://localhost:3333
. You may grant access to any additional origins.
Say you're running your Content Studio on https://studio.mysite.com and want to grant access to that URL. There are two ways of doing this:
- Open your terminal, switch directory to where you keep your Studio source code, then type:
sanity cors add https://studio.mysite.com
- Go to your project settings and add the origin via the web UI. Since you projectId is
6sf5fafo
, these settings can be found at https://manage.sanity.io/projects/6sf5fafo/settings/api
For more on Sanity and CORS, please refer to the documentation at https://www.sanity.io/docs/front-ends/cors
推荐阅读
- arrays - 选择案例语句中的数组是否可能?
- list - InkWell 用于小部件列表?
- c# - 如何诊断缺少的组件?无法加载文件或程序集
- php - 如何自动更新数据库中的列
- mongodb - mongoDB - 在小组赛中获取子字符串并将字符串转换为数字
- javascript - 如何连接 JavaScript 函数以提高浏览器/JS 引擎效率?
- c++ - 从封装在对象中的函数 c++ 返回时为空列表
- zsh - Zsh - 换行后不能退格
- javascript - Show preloading page only once with jQuery
- python - 使用 macOS Automator 从 conda env 中运行 Python 代码的 Shell 脚本