为什么我的浏览器出现 CORS 策略错误? CORS 策略:请求的资源上不存在 'Access-Control-Allow-Origin' header

Why do I have the CORS policy error in my browser? CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

我已经通过 npm 安装了 cors 并使用了 app.use(cors()); 中间件,但这并没有解决我的问题。我是 运行 我在端口 localhost:3000

上的前端 React 应用程序
Access to XMLHttpRequest at 'http://localhost:3087/authenticate-token' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

下面是我的 app.js 文件中的全部代码:

const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require("dotenv");
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
// const request = require('req')

const app = express();

dotenv.config();

// Parse Application/json
app.use(bodyParser.json());

// Base URL
// app.locals.baseURL = "h";

app.use(cors());
app.use(
  session({
    secret: process.env.ACCESS_TOKEN_SECRET,
    saveUninitialized: true,
    resave: false,
    cookie: {
      secure: true,
    },
  })
);

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("MongoDB Connected"))
  .catch((err) => console.log(err));

// Routes
app.use("/", require("./routes/auth"));
app.use("/pages", require("./routes/pages"));
app.use("/signUpModule", require("./routes/signUpModule"));
app.use("/users", require("./routes/users"));

const PORT = process.env.PORT || 3087;

app.listen(PORT, console.log(`Server running on  ${PORT}`));

下面我从我的终点添加了代码:

const express = require("express");

// Authenticate Token
router.get(
  "authenticate-token",
  authFunctions.authenticateToken,
  (req, res) => {
    res.send({user: req.user, tokenValid: true});
);

尝试将此添加到您的 app.js 文件中:

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    // "Access-Control-Allow-Origin",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );

  if (req.method == "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "GET PATCH DELETE POST PUT");
    return res.status(200).json({});
  }

  next();
});

所以,问题恰好来自 client-side,我正在使用 axio 发出请求。起初我有以下内容:

export const userAuthenticated = async (token) => {
  const response = await axios.get(`${API_BASE_URL}/authenticate-token`, {
    headers: {
      authorization: token,
    }
  });
  if (response.statusText === "OK") return response.data;
};

后来,我改成了下面的,效果很好:

export const userAuthenticated = async (token) => {
  const response = await axios({
    headers: {
      authorization: token,
    },
    method: "get",
    url: `${API_BASE_URL}/authenticate-token`,
  });
  if (response.statusText === "OK") return response.data;
};