首页 > 解决方案 > 如何解决 Apollo、Node 和 Next.js 中的 CORS 问题?

问题描述

我需要帮助解决我在 Apollo、Node 和 Next.js 中遇到的 CORS 错误。我不确定我做了什么改变,但突然间我无法从我的 Prisma 数据库中获取数据。我目前正在运行开发模式。我从 Prisma 中提取数据的 Yoga 服务器在 localhost:4444 运行。我的前端在 localhost:7777 上运行。

这是我的 CORS 设置:

import withApollo from "next-with-apollo";
import ApolloClient from "apollo-boost";
import { endpoint, prodEndpoint } from "../config";
import { LOCAL_STATE_QUERY } from "../components/Cart";

function createClient({ headers }) {
  return new ApolloClient({
    uri: process.env.NODE_ENV === "development" ? endpoint : prodEndpoint,
    request: (operation) => {
      operation.setContext({
        fetchOptions: {
          credentials: "include",
        },
        headers,
      });
    },
    // local data
    clientState: {
      resolvers: {
        Mutation: {
          toggleCart(_, variables, { cache }) {
            // read the cartOpen value from the cache
            const { cartOpen } = cache.readQuery({
              query: LOCAL_STATE_QUERY,
            });
            // Write the cart State to the opposite
            const data = {
              data: { cartOpen: !cartOpen },
            };
            cache.writeData(data);
            return data;
          },
        },
      },
      defaults: {
        cartOpen: false,
      },
    },
  });
}

export default withApollo(createClient);

变量.env

FRONTEND_URL="localhost:7777"
PRISMA_ENDPOINT="https://us1.prisma.sh/tim-smith-131869/vouch4vet_dev_backend/dev"
PRISMA_SECRET="..."
APP_SECRET="..."
STRIPE_SECRET="..."
PORT=4444

后端 index.js

const server = createServer();

server.express.use(cookieParser());

// decode the JWT so we can get the user Id on each request
server.express.use((req, res, next) => {
  const { token } = req.cookies;
  if (token) {
    const { userId } = jwt.verify(token, process.env.APP_SECRET);
    // put the userId onto the req for future requests to access
    req.userId = userId;
  }
  next();
});

我曾尝试回滚到以前的提交,但我没有运气。我不排除互联网问题。

如果您需要查看我的其余部分,请告诉我。

谢谢

标签: node.jsgraphqlnext.jsreact-apolloprisma

解决方案


推荐阅读