node、typescript、apollo 和 graphql 的问题

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

我的申请让我很烦恼。我的服务器配置是否不正确? 我正在尝试通过前端在我的 PostgreeSQL 数据库中创建一个用户。我制作了一个 tsx 组件,它是一个表单。当我提交数据时,它返回一个 cors 错误,我的前端位于 localhost:3000,后端位于 localhost:4000。尽管我已经完成了所有配置,但它不起作用。但是,我的预检请求有效,返回代码 204,但我的提取请求无效,它返回 cors 错误。

这是我的代码:

import express from "express";
import cors from "cors";
import { ApolloServer } from "apollo-server-express";
import schema from "../graphql/schema";

const app = express();
const port = process.env.PORT || 4000;

const whitelist = ["http://localhost:3000"];

const corsOptions: cors.CorsOptions = {
  origin: (origin: any, callback: any) => {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      callback(new Error("Not allowed by CORS"));
    }
  },
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  credentials: true,
  optionsSuccessStatus: 204,
};

app.use(cors());

app.get("/", (req, res) => {
  res.send("Hello, World!");
});

const server = new ApolloServer({
  schema,
  context: ({ req, res }) => ({
    req,
    res,
  }),
  plugins: [
    {
      async requestDidStart({ request, context }) {
        return {
          async willSendResponse({ response }) {
            response.http?.headers.set("Apollo-Require-Preflight", "true");
          },
        };
      },
    },
  ],
});

const startServer = async () => {
  await server.start();
  server.applyMiddleware({
    app,
    path: "/graphql",
    cors: false,
  });
  app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
  });
};

startServer();

我的网络: enter image description here

这里出现错误:

localhost/:1 从源“http://localhost:3000”获取“http://localhost:4000/graphql”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“*”。

这是我的第一个带有后端的前端应用程序,这个问题已经困扰我好几天了。奇怪的是,第一次请求已经成功,但第二次却没有成功。我不知道还能尝试什么。预先感谢您的帮助,编码朋友!

node.js typescript graphql cors apollo
1个回答
-1
投票

您需要提供

origin: "http://localhost:3000"

当请求的凭证模式为“include”时,选项中 Origin 的值不能是通配符“*”(来自

true
)。 你需要

callback(null, ['http://localhost:3000/']);
© www.soinside.com 2019 - 2024. All rights reserved.