在apollo服务器rexpress和创建react应用程序中使用cookie时出现CORS问题



我在后端使用apollo服务器express,在前端使用react。我想使用cookie进行身份验证,所以我按照下面的代码设置了我的服务器,这是多个教程和解决方案的结果。尽管如此,当我从前端发送任何请求时,我还是会收到CORS错误。我还尝试添加

"代理":"http://localhost:4000/",

到react应用程序的package.json文件。

在'获取的访问权限http://localhost:4000/graphql'来自原点'http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在"access control Allow Origin"标头。如果不透明响应满足您的需求,请将请求的模式设置为"无cors",以在禁用cors的情况下获取资源。

import { ApolloServer } from "apollo-server-express";
import {
ApolloServerPluginDrainHttpServer,
ApolloServerPluginLandingPageLocalDefault,
} from "apollo-server-core";
import { context } from "./context";
import { schema } from "./schema";
import "dotenv/config";
import express from "express";
import http from "http";
import session from "express-session";
import { v4 as uuidv4 } from "uuid";
const startApolloServer = async () => {
const isProduction = process.env.NODE_ENV === "production";
const app = express();
app.use(
session({
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 1,
httpOnly: true,
sameSite: "none",
secure: true,
},
genid: () => uuidv4(),
secret: process.env.SESSION_SECRET as string,
resave: false,
saveUninitialized: false,
})
);
app.set("trust proxy", true); //process.env.NODE_ENV !== "production");
app.set("Access-Control-Allow-Origin", "https://studio.apollographql.com");
app.set("Access-Control-Allow-Credentials", true);
const httpServer = http.createServer(app);
const plugins = [ApolloServerPluginDrainHttpServer({ httpServer })];
process.env.__dev__ &&
plugins.push(ApolloServerPluginLandingPageLocalDefault());
const server = new ApolloServer({
schema,
//context: ({ req, res }: any) => ({ req, res }),
context,
plugins,
introspection: !isProduction,
});
await server.start();
server.applyMiddleware({
app,
cors: {
origin: ["https://studio.apollographql.com"],
credentials: true,
},
});
await new Promise<void>((resolve) =>
httpServer.listen({ port: process.env.PORT }, resolve)
);
console.log(
`🚀 Server ready at http://localhost:${process.env.PORT}${server.graphqlPath}`
);
};
startApolloServer();

这是我在前端的设置:

consthttpLink=createHttpLink({uri:'http://localhost:4000/graphql',凭据:'include',});

我期待着你的回答!谢谢:(

我终于找到了解决方案。我不得不补充http://localhost:3000到我的cors设置:

server.applyMiddleware({
app,
cors: {
origin: ["https://studio.apollographql.com", "http://localhost:3000"],
credentials: true,
},
});

我仍然想知道为什么没有在所有教程中添加这个?!

最新更新