我正试图制作一个jwt auth api,一切正常,直到今天,给邮递员的投递请求仅返回{}
这是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.use("/api/crud", crud);
app.listen(port, () => {
console.log(`Conectado en el puerto ${port}`);
});
这是auth.js的代码,其中发帖请求给了我{}
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 {
//Encontrar usuario en BD
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("En BD");
}
} catch (error) {}
});
module.exports = router;
答案 0 :(得分:0)
没关系,对于遇到同样问题的任何人,在邮递员中您都必须将标题放入Content-Type:application / json。 我输入了Contetn-Type:application / x-www-form-urlencoded加上前面所说的内容