为什么 CORS 无法在我的 express/react 应用程序上运行?

Why is CORS not working on my express/react app?

我正在将 npm cors 包与我的 React 应用程序和 express(OOP 方法)一起使用,但我仍然收到 CORS 错误:

Access to XMLHttpRequest at 'http://localhost:8000/api/auth/authenticate' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在后端 localhost:8000 设置了 cors()。我在 localhost:3000.

的前端用 { withCredentials: true } 调用 api

所以我不确定哪里出了问题。

下面是我的设置。谢谢,

后端 - express.middleware.ts

import cors from "cors";
import express from "express";

module.exports = (app: any) => {
  app.use(
    cors({
      origin: "http://localhost:3000",
      methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
      credentials: true,
    })
  );

  app.use(express.static("public"));
};

后端 - app.ts

import express from "express";
import dotenv from "dotenv";
import path from "path";

class App {
  private _app: express.Application;
  private readonly _port: number | string = process.env.PORT || 8000;

  constructor(controllers: any[]) {
    this._app = express();
    dotenv.config();

    this.initializeControllers(controllers);
    this.initializeMiddleWares();
  }

  public start() {
    this._app.listen(this._port, () => {
      console.log(`App listening on the port ${this._port}`);
    });
  }

  private initializeControllers(controllers: any[]) {
    controllers.forEach((controller) => {
      this._app.use("/api", controller.router);
    });
  }

  public initializeMiddleWares() {
    require("./src/middleware/express.middleware")(this._app);
  }
}

export default App;

后端 - server.ts

import App from "./app";
import AuthController from "./src/modules/auth/auth.controller";
import { AuthService } from "./src/modules/auth/auth.service";

const server = new App([new AuthController(new AuthService())]);

server.start();

前端 - useGet.ts(自定义钩子调用 api)

import React from "react";
import { useHistory } from "react-router-dom";
import axios from "axios";
import { server_url } from "../constants";

const useGet = () => {
  const history = useHistory();
  const doGet = (path: string, cb?: Function) => {

    axios
      .get(`${server_url}${path}`, { withCredentials: true })
      .then((response) => {
        if (cb) {
          cb(response.data);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return [doGet];
};

export default useGet;

在配置路由之前初始化中间件

来自the docs

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

在你的例子中,控制器确实结束了请求-响应周期,因此中间件永远不会起作用。

要修复它,请更改:

class App {
  // ...
  constructor(controllers: any[]) {
    // ...
    this.initializeControllers(controllers);
    this.initializeMiddleWares();
  }

进入这个(注意行的顺序):

class App {
  // ...
  constructor(controllers: any[]) {
    // ...
    this.initializeMiddleWares();
    this.initializeControllers(controllers);
  }

你应该可以开始了。