最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

当我向我的网站注册一个新用户时,我遇到了这个错误“secretOrPrivateKey必须有一个值”! Node.js的

IT培训 admin 4浏览 0评论

当我向我的网站注册一个新用户时,我遇到了这个错误“secretOrPrivateKey必须有一个值”! Node.js的

我正在尝试为应用程序注册一个新用户,但我总是得到这个错误“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

这是我使用密钥的地方:

    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 userparePassword(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
    });
  }
};

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

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

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

回答如下:

SECRET_KEY = urethndvkngkjdbgkdkdnbdmbmdbdf

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

当我向我的网站注册一个新用户时,我遇到了这个错误“secretOrPrivateKey必须有一个值”! Node.js的

我正在尝试为应用程序注册一个新用户,但我总是得到这个错误“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

这是我使用密钥的地方:

    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 userparePassword(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
    });
  }
};

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

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

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

回答如下:

SECRET_KEY = urethndvkngkjdbgkdkdnbdmbmdbdf

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

发布评论

评论列表 (0)

  1. 暂无评论