reactjscorssanity

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.


Solution

  • 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:

    1. Open your terminal, switch directory to where you keep your Studio source code, then type:
    sanity cors add https://studio.mysite.com
    
    1. 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