NodeJS 为一条路由启用cors,而其他路由保持不变

uajslkp6  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(70)

我有一个Express应用程序,这是我如何配置它的

// app.js file
const corsConfig = { origin: process.env.FRONT_END }
app.use(cors(corsConfig));
app.options("*", cors(corsConfig));

app.use("/api/v1/users", userRouter);
app.use("/api/v1/projects", projectRouter);
app.use("/api/v1/leads", leadRouter);

// in leadRouter.js file
const cors = require("cors");
const express = require("express");
const router = express.Router();

router.get("/", authController.protect, leadController.getLeads);
router.options("/:projectId", cors({origin: true}));
router.post("/:projectId", cors({origin: true}), leadController.createLead);

字符串
我想向所有人开放/api/v1/leads/:projectId,同时保留之前配置的其他路由。但是我当前的配置不起作用,当在api/v1/leads/:projectId上发布时,我得到了preflight cors错误
在前端,我使用axios,它可能会在发送请求时设置'authorization'头。有什么解释吗?

5kgi1eie

5kgi1eie1#

const express = require("express");
const router = express.Router();

// This route will allow cross-origin requests for everyone
router.options("/:projectId", (req, res) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.status(200).send();
});

router.get("/", authController.protect, leadController.getLeads);

// No need to use cors middleware for the route below, as we already set the headers in the options route.
router.post("/:projectId", leadController.createLead);

module.exports = router;

字符串

相关问题