【发布时间】: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