Today, I encountered an issue while trying to create a JWT authentication API in Express. When I send a POST request with Postman, it only returns {}.
Below is the code for server.js:
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const app = express();
const auth = require("./rutas/auth");
dotenv.config();
const port = process.env.PORT || 5000;
mongoose.connect(process.env.URI, {
useUnifiedTopology: true,
useNewUrlParser: true
});
app.use(express.json());
app.use("/api/auth", auth);
app.listen(port, () => {
console.log(`Connected on port ${port}`);
});
And here is the code for auth.js where the POST request returns {}:
const express = require("express");
const { check, validationResult } = require("express-validator");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../modelos/User");
router.get("/", async (req, res) => {
const usuarios = await User.find();
res.send(usuarios);
});
router.post("/sign", async (req, res) => {
const { nombre, email, contraseña } = req.body;
res.json(req.body);
console.log(req.body);
});
router.post("/login", [], async (req, res) => {
const { email, contraseña } = req.body;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
try {
const usuario = await User.findOne({ email });
const isValido = await bcrypt.compare(contraseña, usuario.contraseña);
if (isValido) {
const payload = {
id: usuario._id
};
const token = jwt.sign(payload, "secretomagico", { expiresIn: "1h" });
req.header("auth-token", token);
res.send("In DB");
}
} catch (error) {}
});
module.exports = router;
I also provided the JSON message sent via Postman:
{ "nombre":"Jack", "contraseña":12345678, "email":"[email protected]" }