最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

错误:“secretOrPrivateKey 必须在 module.exports 中有一个值 [as sign]”

网站源码admin45浏览0评论

错误:“secretOrPrivateKey 必须在 module.exports 中有一个值 [as sign]”

错误:“secretOrPrivateKey 必须在 module.exports 中有一个值 [as sign]”

我没有在控制台中获得任何令牌和 cookie,而是显示此错误。

userSchema.js:

const JWT_SECRET = process.env.JWT_SECRET;

const userSchema = new mongoose.Schema({
 tokens: [
    {
      token: {
        type: String,
        required: true,
      },
    },
  ],
});
// generting token
userSchema.methods.generateAuthToken = async function () {
  try {
    let token = jwt.sign({ _id: this._id }, JWT_SECRET, {
      expiresIn: "1d",
    });
    this.tokens = this.tokens.concat({ token: token });
    await this.save();
    return token;
  } catch (error) {
    console.log(error);
  }
};

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

module.exports = User;

相关代码来自controller.js

const Products = require("../models/productSchema");
const User = require("../models/userSchema");
const bcrypt = require("bcryptjs");



const loginController = async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    res.status(400).json({
      error: "Fill the data",
    });
    // console.log("No data available");
  }

  try {
    const userlogin = await User.findOne({ email: email });
    // console.log(userlogin);
    if (userlogin) {
      const isMatch = await bcryptpare(password, userlogin.password);
      console.log(isMatch);

      if (!isMatch) {
        res.status(400).json({ error: "Invalid crediential pass" });
      } else {
        const token = await userlogin.generateAuthToken();
        console.log(token);

        res.cookie("Amazon_website", token, {
          expires: new Date(Date.now() + 1800000),
          httpOnly: true,
        });
        res.status(201).json(userlogin);
      }
    } else {
      res.status(400).json({ error: "User doesn't exist" });
    }
  } catch (error) {
    res.status(400).json({
      error: "Invalid Details",
    });
  }
};

错误:

我只想使用 JSON Web Token 生成令牌和 cookie,并在用户尝试登录时使用此代码生成 cookie。登录工作正常,但未生成令牌。因此,我正在寻找一种有效的解决方案来解决我在这里面临的问题。那么,有人可以帮助我吗?

回答如下:
发布评论

评论列表(0)

  1. 暂无评论