在 apollo-server-rexpress 和 create-react-app 中使用 cookie 时出现 CORS 问题

发布于 2025-01-19 22:15:01 字数 2268 浏览 4 评论 0原文

我在后端使用 apollo-server-express 并在前端进行反应。我想使用 cookie 进行身份验证,因此我像下面的代码一样设置了我的服务器,这是多个教程和解决方法的结果。当我从前端发送任何请求时,我仍然收到 CORS 错误。 我也尝试添加

“代理”:“http://localhost:4000/”,

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

从源“http://localhost:3000”获取“http://localhost:4000/graphql”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“ Access-Control-Allow-Origin'标头存在于所请求的资源上。如果不透明响应满足您的需求,请将请求模式设置为“no-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(
    `
              

I am using apollo-server-express in the backend and react in the frontend. I want to use cookies for authentication so I set up my server like in the code below, which is the result of multiple tutorials and workarounds. Still when I am sending any request from the frontend, I am getting a CORS error.
I also tried adding

"proxy": "http://localhost:4000/",

to the package.json file of the react app.

Access to fetch at 'http://localhost:4000/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

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();

That's my setup in the frontend:

const httpLink = createHttpLink({
uri: 'http://localhost:4000/graphql',
credentials: 'include',
});

I am looking forward to your answers! Thank you :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扎心 2025-01-26 22:15:01

我终于找到了解决方案。我必须将 http://localhost:3000 添加到我的 cors 设置中:

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

我仍然想知道为什么所有教程中都没有添加此内容?!

I finally found the solution. I had to add http://localhost:3000 to my cors settings:

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

I am still wondering why this was not added in all the tutorials?!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文