简体   繁体   中英

I am having this error when I signup a new user to my web site“secretOrPrivateKey must have a value”! Node.js

I am trying to sign up a new user to the app, but i always got this error "secretOrPrivateKey must have a value". the sever working good when i click signup but at the same time, it threw this error. I attached below the output from my terminal when I signup a new user!

this is the index.js file

    // 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}`);
});

this is the .env file :

SECRET_KEY = urethndvkngkjdbgkdkdnbdmbmdbdf

Here is where I am using the secret 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
    });
  }
};

When I sign up a new user it worked and the user added to the DB but still get the error i mentioned "secret or private key must have a value":

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

Remove the spaces around = . In shell-land (which dotenv is emulating), you don't use spaces when assigning values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM