【问题标题】:When I run my node js application the cookie isn't saved in Chrome browser当我运行我的节点 js 应用程序时,cookie 没有保存在 Chrome 浏览器中
【发布时间】:2021-07-20 10:32:34
【问题描述】:

当我通过router.post("/signin", async (req, res) 请求时,cookie 尚未保存在我的本地 Chrome 浏览器中。请帮忙解决这个问题。

const express = require("express");
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt= require('jsonwebtoken')

const User = require("../UserSchema/Schma");
const cookieParser = require("cookie-parser");

router.use(cookieParser());


router.post("/signin", async (req, res) => {
  console.log(req.body);
  try {
    const { email, password } = req.body;
    if (!email || !password) {
      res.json({ error: "invalid credentials you added " });
    }
    const details = await User.findOne({ email: email });
    console.log(details);
    if (!details) {
      res.json({ error: "users error" });
    }
    else
    {
      const isMatch = await bcrypt.compare(password,details.password);
      console.log(isMatch);
      const token= await details.generateAuthToken();
      console.log(token);
      res.cookie("jwtoken",token,{
          expiresIn:"1h",
          httpOnly:false,
          secure:false
        }
      );
      // res.cookie("rememberme", "1", { maxAge: 900000, httpOnly: true });
      if (!isMatch) {
        res.status(400).json({ error: "invalid credientials" });
      }
      else
      {
        res.json({ message: "user signin successfully" });
      }
    }
  }
  catch {
    console.log("something going bad");
    res.status(400).json({ error: "sorry something missing" })
  }
});

我的函数generateAuthToken()在这里

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const jwt= require("jsonwebtoken");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    require:true,
  },
  email: {
      type: String,
      require:true,
  },
  phone :{
      type:Number,
      require:true,
  },
  work:{
      type:String,
      require:true,
  },
  password:{
      type:String,
      require:true,
  }
  ,
  cpassword:{
      type:String,
      require:true,
  },
  tokens:[{
      token:{
          type:String,
          require:true,
      }
  }]
});



userSchema.pre('save', async function(next) {

    if(this.isModified('password'))
    {
        this.password=await bcrypt.hash(this.password,12);
        this.cpassword=await bcrypt.hash(this.cpassword,12);
    }
    next();
})

userSchema.methods.generateAuthToken= async function(){
    try {
        let token= jwt.sign({_id:this._id},process.env.SECRET_KEY);
        this.tokens=this.tokens.concat({token:token});
        await this.save();
        return token;
    } catch (error) {
        console.log(err);
    }
}

const User = mongoose.model("USER", userSchema);
module.exports = User;

【问题讨论】:

    标签: javascript node.js reactjs api google-api-nodejs-client


    【解决方案1】:

    也许您需要分享您的用户模型,但不能说那里发生了什么。也许问题就在这里const token= await details.generateAuthToken(); 无法说出您的 generateAuthToken() 函数中发生了什么。 好吧,你可以试试下面的代码;

     const token = jwt.sign({id: details._id}, process.env.JWT_SECRET(Your JWT Secret), { 
                       expiresIn: "1h" })
                     res.cookie("token", token, {
                     httpOnly: false,
                     secure: false,  
                   })
                  res.status(200).json({ message: "user signin successfully"})
    

    这对我来说很好。 另外,在设置令牌之前尝试使用这个 if 语句

    if (!isMatch) {res.status(400).json({ error: "invalid credientials" })}
    

    在检查密码之前设置令牌有什么意义。

    【讨论】:

    • 我更新了我的问题。请再次访问代码。实施您的代码后。问题仍然存在
    • 看起来你的 generateAuthToken() 函数没问题,然后确保你在根 index.js 或 server.js 上使用了这个app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); res.setHeader('Access-Control-Allow-Credentials', true); next(); });。如果您仍然看到该问题,那么我会说更改您的浏览器并检查。代码看起来不错应该没有问题。
    猜你喜欢
    • 2022-11-02
    • 2021-07-20
    • 2019-08-29
    • 1970-01-01
    • 2018-08-20
    • 2011-08-13
    • 2023-01-25
    • 2017-06-30
    • 2015-03-28
    相关资源
    最近更新 更多