ReactJS + Apollo Client 跨域问题

3
在尝试将GraphQL集成到ReactJS应用程序中时,遇到了CORS问题。
情况如下:
我正在尝试执行一个简单的GraphQL查询,没有使用数据库。如果没有GraphQL实现,程序可以正常工作。
浏览器:Google Chrome版本78.0.3904.87
电脑:MacBook Pro,中期2015年
相关依赖项:
- apollo-boost: 0.4.4 - apollo-client: 2.6.4 - cors: 2.8.5 - express: 4.17.0 - graphql: 14.5.8 - react: 16.8.6 - react-apollo: 3.1.3
这是我在浏览器控制台中收到的错误:
OPTIONS http://localhost:5000/graphql net::ERR_CONNECTION_REFUSED
请在此处查看存储库/目录结构:

https://github.com/curtisyungen/hh-graphql

这是我的 server.js 文件的内容:
const express = require("express");
const graphqlHTTP = require('express-graphql');
const schema = require('./src/graphql/schema');
const cors = require('cors');

const PORT = 5000;

const app = express();

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

app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}. Visit http://localhost:${PORT}/ in your browser.`);
});

module.exports.app = app;

这是我在App.js文件中设置Apollo Client的方式:
const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'http://localhost:5000/graphql'
});

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

这是浏览器中网络选项卡的屏幕截图: 浏览器中网络选项卡的屏幕截图 我已经在互联网上搜寻了解决方案,并尝试了以下方法:
  • app.use(cors());
  • 将 fetchOptions: { mode: 'no-cors' } 添加到 Apollo Client
  • 在 Chrome 中添加 Access-Control-Allow-Origin 扩展程序
  • 使用本地 IP 地址代替“localhost”
我正在跟随一个 YouTube 教程,那个人通过导入 cors 解决了这个问题。他成功了,但我没有……有什么想法吗?

你能分享一下你的目录结构吗? - undefined
@OzanManav 你可以在这里查看代码库:https://github.com/curtisyungen/hh-graphql - undefined
1个回答

0

这里的问题是,你正在从你的 reactjs 前端调用一个 API。

而你的后端没有配置以接受来自不同域名的请求。

你需要通过在服务器配置中添加相关的头部信息来允许这样的请求。

或者,在你的 reactjs 的 package.json 文件中添加以下几行:

"proxy": "http://localhost:5000", # should be the base api url path 

你可以在这里检查我写的文章 https://minasami.com/2021/06/10/cors-errors-fix-with-reactjs.html,该文章与编程有关。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接