Apollo Server v4 抛出 Cors 问题

问题描述 投票:0回答:1

我在访问后端时遇到典型的 CORS 问题

这是我的后端代码

const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

await server.start();

app.use(
  "/graphql",
  cors({
    origin: "http://localhost:3000/",
    credentials: true,
  }),
  express.json(),
  expressMiddleware(server)
);

await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));

console.log("Server started at ", 4000);

这是我的前端代码

第一种方式:

const client = new ApolloClient({
    cache: new InMemoryCache(),
  
    link: new HttpLink({
      uri: "https:/localhost:4000/graphql",
      
    }),
  });

第二种方式

const client = new ApolloClient({
    uri: "https:/localhost:4000/graphql",
    cache: new InMemoryCache(),
  });

两种方法均已尝试,但问题仍然存在

javascript express graphql apollo-client apollo-server
1个回答
0
投票

尝试在服务器设置中指定 CORS

origin: "http://127.0.0.1:3000"
还要注意你的协议是否正确指定了http和https。

© www.soinside.com 2019 - 2024. All rights reserved.