NodeJS 这是设置后端配置的正确方法吗?

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

在下面的例子中,我有我的应用程序的后端设置,但我有问题可能与CORS。
所以问题是我的cookie不会在浏览器中设置,我在Postman和Insomnia上测试了这个,一切都很清楚,我认为这是因为Postman和Insomnia忽略CORS,但brwsers不这样做。
我不知道我的后端是好的,我应该改变一些东西,我尝试了一些其他的东西,如允许 * 地址,添加属性到app.use(cors());和没有帮助。

const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const usersRouter = require("./routes/users");
const authRouter = require("./routes/auth");
const logoutRouter = require("./routes/logout");
const vehicleRouter = require("./routes/vehicle");
const dashboardRouter = require("./routes/dashboard");

app.use(express.json());

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8080"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.use(cors());

app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(
  session({
    key: "userId",
    secret: "sistem",
    resave: false,
    saveUninitialized: false,
    cookie: {
      expires: 60 * 60 * 24,
    },
  })
);

app.use("/", authRouter);
app.use("/", usersRouter);
app.use("/", logoutRouter);
app.use("/", vehicleRouter);
app.use("/", dashboardRouter);

app.listen(3000, () => {
  console.log("Server je pokrenut");
});

字符串
我希望你能帮助我,并最终解决这个错误。
顺便说一句,这是我的整个index.js文件,其他路由都在单独的文件夹中,就像DB连接一样,我认为这是一种更干净的方法。

hpxqektj

hpxqektj1#

这应该可以工作:

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT');
    res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
    next();
});
app.use(cors());

字符串

相关问题