[英]The app works fine with localhost but Heroku gives bad request error when trying to login or signup with post
我有我的第一個 node.js 應用程序(在本地運行良好) - 但是 Heroku 在嘗試登錄或注冊時出現 Bad Request(400) 錯誤(也是第一次使用 heroku)。 代碼如下。 我會說在本地運行代碼以及在我的網絡中運行都沒有問題。 我不明白問題是否來自前端請求。
和代碼: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}`);
});
身份驗證.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;
配置文件:
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",
},
};
常量.js:
require("dotenv").config();
module.exports = {
SALT_ROUNDS: 10,
PORT: process.env.PORT || 4000,
};
簡介:
release: bash post-release.sh
發布后.sh:
npx sequelize-cli db:migrate
我也有一個 .env 文件
DB_URL=postgres....
JWT_SECRET=....
任何的想法?
我已經看到在 AUTH MIDDLEWARE JsonWebTokenError 中有一個錯誤:必須提供秘密或公鑰。 這意味着我的應用程序無法正確讀取環境變量。 我已經解決了這個問題以更改為 JWT 功能。 它使用 jwt.sign(data, jwtSecret, {expiresIn: "1h"}) 函數。 我已經將 jwtSecret 更改為 "" + jwtSecret,就像在那里的繼承一樣: https ://stackoverflow.com/a/62350806/15018495
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.