mongodb 无法在浏览器上设置cookie

to94eoyn  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(228)

我正在创建一个博客网站,通过检查存储在cookie中的jwt令牌来验证用户。它在我的本地机器上工作正常,但当我在Azure VM上部署后端并在Azure应用服务上部署前端时,这就是导致问题的原因,浏览器无法在浏览器上设置cookie。
下面是index.js的代码
const express = require(“express”);
const dbconnection = require(“./database/dbconnect”);
const authRoute = require(“./routes/authRoutes.js”);
const bodyParser = require(“body-parser”);
const userRoute = require(“./routes/userRoute.js”);
const blogRoute = require(“./routes/blogRoute.js”);
cookieParser = require(“cookie-parser”);
const cors = require(“cors”);
int count = 8000;
getString();
const app = express();
app.use(bodyParser.json({ extended:true }));
//app.setHeader(“验证-控制-允许-凭证”,“true”);
app.use((req,res,next)=> {
//设置CORS头
res.header(“控制-允许-起源”,process.env.FRONTEND_URL); //替换为您的前端域
res.header(“GET,POST,PUT,POST”);
res.header(“Content-Control-Allow-Headers”,“Content-Type,Authorization”);
res.header(“site-Control-Allow-Credentials”,“true”); //允许凭证(cookie等)
//传递到中间件的下一层
return();
});
app.use(bodyParser.urlencoded({ extended:true }));
app.use(cookieParser);
app.use(“/");
app.use(“/user”,userRoute);
app.use(“/blogRoute”,blogRoute);
app.listen(PORT,()=> {
console.log(Server is running on port ${PORT});
});
下面是login.js的代码
const User = require(“../database/model/user”);
const bcrypt = require(“bcrypt”);
const env = require(“dotenv”);
const {tokenSecretToken} = require(“tokenGeneration/generateToken”);
public void run();
const login = logic(req,res)=> {
const { email,password } =请求体;
if(!(email && password)){
return res.status(400).json({ message:“所有输入都是必需的”});
}
const user = await User.findOne({ email });
if(!(user &&(await bcrypt.compare(password,user.password){
return res.status(404).json({ message:“Invalid credentials”});
}
const token = new SecretToken(user._id);
console.log(token)
res.cookie(“token”,token,{
域名:“. bloggle-vista.azurewebsites.net”,
路径:“/",
httpOnly:true,
安全:真,
sameSite:“无”
});
res.json({ token });
};
modules.exports = login;

ztigrdn8

ztigrdn81#

使用jwt token而不是这个

/* status codes */
const {
  ReasonPhrases,
  StatusCodes,
  getReasonPhrase,
  getStatusCode,
} = require("http-status-codes");
const JWT = require("jsonwebtoken");
/* dotenv */
const dotenv = require("dotenv");
    // dotEnv Configuration
dotenv.config();
/* models */
const User = require("../models/user.model");
const signToken = (id) => {
  return JWT.sign({ id }, process.env.JWT_SEC, {
    expiresIn: process.env.expirydateJwt,
  });
};

字符串
jwt token被广泛接受用于完成此工作
使用signToken函数获取令牌
make .env文件

JWT_SEC=Abdul Wadood
expirydateJwt=3d
CRYPTO_SEC=Abdul Wadood


下载dotenv和jsonwebtoken包
软件包:

npm i jsonwebtoken dotenv

相关问题