我正在使用express-session
处理这个NodeJS项目,为我的应用程序创建会话。问题是,当我向http://localhost:5500/login
发出post
请求时,会使用我有意添加的附加属性userid
创建会话。然后,当我使用Postman向http://localhost:5500/
发出get
请求时,应用程序实际上接收带有属性userid
的会话,并根据userid
是否设置将用户重定向到其主页。但是,如果我从Chrome等浏览器向http://localhost:5500/
发出get
请求,我的服务器无法获取我在成功登录时添加的附加属性'userid'的会话,并且无法将我的用户重定向到他的主页。有人能解释一下为什么会发生这种情况吗?谢谢
下面是我的index.js
'的代码
const express = require("express")
const app = express()
const PORT = process.env.PORT || 5500
const session = require("express-session")
const { routers } = require("./routes/routes")
const mongoose = require("mongoose")
const cookieParser = require("cookie-parser")
const TIME = 1000 * 60 * 5
app.use(cookieParser())
app.use(
session({
secret: "iamnamdo1234567",
saveUninitialized: true,
cookie: { maxAge: TIME, sameSite: "strict" },
resave: false
})
)
const URI = process.env.DB_CONNECTION
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use("/api", routers)
app.get("/", (req, res) => {
let session = req.session.userid
session ? res.status(200).send("Hello my friend, you are logged in") : res.status(400).send("You need to log in")
})
mongoose.connect(URI, { useNewUrlParser: true.valueOf(), useUnifiedTopology: true }, err => {
if (err) {
console.log(err)
} else {
console.log("database connected")
}
})
app.listen(PORT, () => {
console.log(`Go to http://localhost:${PORT}`)
})
'
这是我的routes.js
'的代码
const express = require("express")
const route = express.Router()
const { User } = require("../models/User")
const bcrypt = require("bcrypt")
const errorHandler = (type, error) => {
if (type === "register") {
if (error.code === 11000) {
return { message: "Username has been taken" }
} else if (error._message === "User validation failed") {
return { message: error.errors.username?.properties.message || error.errors.password?.properties.message }
}
} else if (type === "login") {
return { message: `${error}` }
}
}
route.post("/register", async (req, res) => {
try {
const { username, password } = req.body
const user = await User.create({ username, password })
res.status(200).send("User has been created successfully")
} catch (error) {
// console.log(error)
let message = errorHandler("register", error)
res.status(400).send(message)
}
})
route.post("/login", async (req, res) => {
const { username, password } = req.body
try {
const user = await User.findOne({ username })
if (!user) {
throw (new Error().message = "Username not found")
}
const checkPassword = await bcrypt.compare(password, user.password)
if (checkPassword === false) {
throw (new Error().message = "Password is incorrect")
} else {
req.session.userid = user.username
console.log(req.session.userid)
res.status(200).send("Logged in")
}
} catch (error) {
let message = errorHandler("login", error)
res.status(400).send(message)
}
})
route.post("/logout", (req, res) => {
req.session.destroy()
res.redirect("/")
})
module.exports.routers = route
'
我尝试在从浏览器发出get
请求时访问会话
1条答案
按热度按时间t3irkdon1#
如果会话细节在Postman中可见,但在浏览器中不可见,这可能是由于多种原因,其中之一是Cookie策略。默认情况下,Cookie只在与当前页面相同的源发出请求时发送。要在跨源请求中发送Cookie,您需要在Axios中设置withCredentials选项。尝试一下,我觉得它很有效
常量axios =要求(“axios”);
axios.默认值.withCredentials =真;