CORS 策略阻止了从来源 'http://localhost:3000' 在 'http://localhost:6969/graphql' 获取的访问权限:

Access to fetch at 'http://localhost:6969/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy:

这是错误的补充部分 -> 请求的资源上不存在 'Access-Control-Allow-Origin' header。如果不透明响应满足您的需求,请将请求的模式设置为 'no-cors' 以在禁用 CORS 的情况下获取资源。

我在 Apollo Client 的帮助下学习 Graphql 和 React js, 这是我的 Server.js 代码:-

const express = require("express");
const app = express();
const PORT = 6969;
const userData = require("./MOCK_DATA.json");
const schema = require("./Schemas/index.js")
const graphql = require("graphql");

const {
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLInt,
    GraphQLString,
    GraphQLList
} = graphql
const {graphqlHTTP} = require('express-graphql')

 
app.use('/graphql', graphqlHTTP({
    schema,
    graphiql: true
}))


app.listen(PORT, () => {
    console.log("Server Running");
})

这是我的 App.js 文件,用于显示获取的数据:-

import React from 'react';
import './App.css';
import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink, from } from '@apollo/client'
import {onError} from '@apollo/client/link/error';
import GetUser from './Components/GetUser';


const errorLink = onError(({ graphqlErrors, networkError }) => {
  if (graphqlErrors) {
    graphqlErrors.map(({ message, location, path }) => {
      alert(`Graphql error ${message}`);
    });
  }
});

const link = from([
  errorLink,
  new HttpLink({ uri: "http://localhost:6969/graphql" }),
]);

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: link,
});

function App() {
  return (
    <ApolloProvider client={client }>
      <GetUser/>
    </ApolloProvider>
  );
}

export default App;

据我所知,您应该授予对后端文件 http://localhost:3000 的访问权限。 但是,你的问题。

同时检查以下内容:

CORS issue with using localhost:3000 to access graphql API at a different URL

CORS error: Access to fetch backend to frontend, Graphql (Nodejs, Reactjs)