在尝试将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
请在此处查看存储库/目录结构:
这是我在App.js文件中设置Apollo Client的方式:
这是浏览器中网络选项卡的屏幕截图: 浏览器中网络选项卡的屏幕截图 我已经在互联网上搜寻了解决方案,并尝试了以下方法:
情况如下:
我正在尝试执行一个简单的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”