该应用程序在localhost上运行良好,但Heroku在尝试登录或使用post注册时会出现错误请求



我有我的第一个node.js应用程序(在本地运行良好(,但Heroku在尝试登录或注册时(也是第一次Heroku(会出现Bad Request(400(错误。代码如下。我想说,在我的网络中本地运行代码没有问题。我不明白问题是否来自前端请求。

代码:index.js:

const express = require("express");
const loggerMiddleWare = require("morgan");
const cors = require("cors");
const { PORT } = require("./config/constants");
const authRouter = require("./routers/auth");
const artworkRouter = require("./routers/artworks");
const bodyParserMiddleWare = express.json();
const app = express();
app.use(loggerMiddleWare("dev"));
app.use(bodyParserMiddleWare);
app.use(cors());
if (process.env.DELAY) {
app.use((req, res, next) => {
setTimeout(() => next(), parseInt(process.env.DELAY));
});
}
app.use("/", authRouter);
app.use("/artworks", artworkRouter);
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`);
});

auth.js

const bcrypt = require("bcrypt");
const { Router } = require("express");
const { toJWT } = require("../auth/jwt");
const authMiddleware = require("../auth/middleware");
const User = require("../models/").user;
const { SALT_ROUNDS } = require("../config/constants");
const router = new Router();
router.post("/login", async (req, res, next) => {
try {
console.log(`Before const { email, password } = req.body;`);
const { email, password } = req.body;
console.log(`After const { email, password } = req.body;`);
if (!email || !password) {
return res
.status(400)
.send({ message: "Please provide both email and password" });
}
console.log(`Before await User.findOne({ where: { email } });`);
const user = await User.findOne({ where: { email } });
console.log(`After await User.findOne({ where: { email } });`);
if (!user || !bcrypt.compareSync(password, user.password)) {
return res.status(400).send({
message: "User with that email not found or password incorrect",
});
}
delete user.dataValues["password"]; // don't send back the password hash
const token = toJWT({ userId: user.id });
return res.status(200).json({ token, ...user.dataValues });
} catch (error) {
console.log(error);
return res.status(400).send({
message: `Login Page: Something went wrong, sorry: ${JSON.stringify(
req.headers
)}, AND, ${JSON.stringify(req.body)}
)}`,
});
}
});
router.post("/signup", async (req, res) => {
const { email, password, name, isArtist } = req.body;
if (!email || !password || !name) {
return res.status(400).send("Please provide an email, password and a name");
}
try {
const newUser = await User.create({
email,
password: bcrypt.hashSync(password, SALT_ROUNDS),
name,
isArtist,
});
delete newUser.dataValues["password"]; // don't send back the password hash
const token = toJWT({ userId: newUser.id });
res.status(201).json({ token, ...newUser.dataValues });
} catch (error) {
if (error.name === "SequelizeUniqueConstraintError") {
return res
.status(400)
.send({ message: "There is an existing account with this email" });
}
return res
.status(400)
.send({ message: "Signup Page: Something went wrong, sorry" });
}
});
module.exports = router;

config.js:

require("dotenv").config();
module.exports = {
development: {
url: process.env.DB_URL,
dialect: "postgres",
operatorsAliases: "0",
},
test: {
username: "root",
password: null,
database: "database_test",
host: "127.0.0.1",
dialect: "postgres",
operatorsAliases: "0",
},
production: {
use_env_variable: "DATABASE_URL",
dialectOptions: {
ssl: {
rejectUnauthorized: false,
},
},
dialect: "postgres",
},
};

constants.js:

require("dotenv").config();
module.exports = {
SALT_ROUNDS: 10,
PORT: process.env.PORT || 4000,
};

Procfile:

release: bash post-release.sh

post-release.sh:

npx sequelize-cli db:migrate

我还有一个.env文件

DB_URL=postgres....
JWT_SECRET=....

知道吗?

我看到auth中间件中有一个错误:

JsonWebTokenError:必须提供密钥或公钥。

这意味着我的应用程序无法正确读取环境变量。我已经解决了这个问题来更改toJWT函数。它使用jwt.sign(data, jwtSecret, { expiresIn: "1h" })函数。我变了jwtSecret作为"" + jwtSecret如在继承中那样:https://stackoverflow.com/a/62350806/15018495.

最新更新