javascript - 当我向我的网站注册新用户时,出现此错误“secretOrPrivateKey 必须具有值”! Node.js

标签 javascript node.js mongodb secret-key

我正在尝试向应用程序注册新用户,但总是收到此错误“secretOrPrivateKey 必须有值”。当我单击注册时,服务器运行良好,但同时,它引发了此错误。当我注册新用户时,我在下面附加了终端的输出!

这是index.js 文件

    // load environment variables
require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const errorHandler = require("./handlers/error");
const authRoutes = require("./routes/auth");
const messagesRoutes = require("./routes/messages");
const { loginRequired, ensureCorrectUser } = require("./middleware/auth");
const db = require("./models");
const PORT = process.env.PORT || 8081;

app.use(cors());
app.use(bodyParser.json());

app.use("/api/auth", authRoutes);
app.use(
  "/api/users/:id/messages",
  loginRequired,
  ensureCorrectUser,
  messagesRoutes
);

app.get("/api/messages", loginRequired, async function(req, res, next) {
  try {
    let messages = await db.Message.find()
      .sort({ createdAt: "desc" })
      .populate("user", {
        username: true,
        profileImageUrl: true
      });
    return res.status(200).json(messages);
  } catch (err) {
    return next(err);
  }
});

app.use(function(req, res, next) {
  let err = new Error("Not Found");
  err.status = 404;
  next(err);
});

app.use(errorHandler);

app.listen(PORT, function() {
  console.log(`Server is starting on port ${PORT}`);
});

这是 .env 文件:

SECRET_KEY = urethndvkngkjdbgkdkdnbdmbmdbdf

这是我使用 key 的地方:

    const db = require("../models");
const jwt = require("jsonwebtoken");

exports.signin = async function(req, res, next) {
  try {
    // finding a user
    let user = await db.User.findOne({
      email: req.body.email
    });
    // Destructure some properties from the user
    let { id, username, profileImageUrl } = user;
    let isMatch = await user.comparePassword(req.body.password);
    // checking if their Password matches what we sent to the server
    if (isMatch) {
      // will make the token
      let token = jwt.sign(
        {
          id,
          username,
          profileImageUrl
        },
        process.env.SECRET_KEY
      );
      return res.status(200).json({
        id,
        username,
        profileImageUrl,
        token
      });
    } else {
      return next({
        status: 400,
        message: "Invalid Email/Password."
      });
    }
  } catch (e) {
    return next({ status: 400, message: "Invalid Email/Password." });
  }
};

exports.signup = async function(req, res, next) {
  try {
    // create a user using the user model
    let user = await db.User.create(req.body);
    let { id, username, profileImageUrl } = user;
    // create a token(signing a token)
    let token = jwt.sign(
      {
        id,
        username,
        profileImageUrl
      },
      // after siging in that object, pass the secret key
      process.env.SECRET_KEY
    );
    return res.status(200).json({
      id,
      username,
      profileImageUrl,
      token
    });
  } catch (err) {
    // if the validation fails
    if (err.code === 11000) {
      // respond with this msg
      err.message = "Sorry, that username and/or email is taken";
    }
    return next({
      status: 400,
      message: err.message
    });
  }
};

当我注册一个新用户时,它起作用了,用户添加到了数据库,但仍然收到我提到的错误“ secret 或私钥必须有一个值”:

Mongoose: users.insert({ messages: [], _id: ObjectId("5c797464ef55a33c70207df3"), email: 'test@test.com', username: 'test', password: '$2a$10$kU2QVvCMGWv84JbhD8DYs.QNVwQXeDvhxAmUPvLSA4TytiFqvNlkC', profileImageUrl: '', __v: 0 })
Mongoose: users.findOne({ email: 'test@test.com' }, { fields: {} })
Mongoose: users.insert({ messages: [], _id: ObjectId("5c797490ef55a33c70207df4"), email: 'test222@test.com', username: 'test222', password: '$2a$10$ALqubvIZ2xRSUr5GputTY.uRxQ77cGW9Fcgc8zlOjJ/aq3CBn1bj6', profileImageUrl: '', __v: 0 })
Mongoose: users.insert({ messages: [], _id: ObjectId("5c7974dfef55a33c70207df5"), email: 'test2222@test.com', username: 'test2222', password: '$2a$10$QKXt9EsOPMNDfubP4UuT8OK6tksz59ZZFYtHFY7AyfDh5zEiO2jWa', profileImageUrl: '', __v: 0 })

点击注册时出现错误的屏幕截图

a screenshot from the error when i click on signup

最佳答案

SECRET_KEY = urethndvkngkjdbgkdkdnbdmbmdbdf

删除 = 周围的空格。在 shell-land(dotenv 正在模拟)中,赋值时不使用空格。

关于javascript - 当我向我的网站注册新用户时,出现此错误“secretOrPrivateKey 必须具有值”! Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54970418/

相关文章:

javascript - 如何在 Firebase 可调用云函数上引发自定义错误?

node.js - 事务中的 Google Datastore Transaction API 与 Datastore API

javascript - 修改 Woocommerce Javascript

node.js - Node v0.5.0 pre Socket.IO 在连接时崩溃(与传输无关)

javascript - 如何根据 JavaScript 中的其他数据值获取 JSON 数据

php - 为什么 php-mongodb 扩展无法工作?

mongodb - MongoDB : how to select items with nested array count > 0

mongodb - 使用 where 条件聚合查询

javascript - onclick 时更改按钮文本

javascript - 如何解决 Uncaught TypeError : this. 过滤器不是函数? (vue.js 2)