Express API在发布请求中未返回任何内容

时间:2019-12-10 19:41:20

标签: javascript rest api express postman

我正试图制作一个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;
这是我在邮递员中发送的json消息: { “ nombre”:“ Jack”, “contraseña”:12345678, “电子邮件”:“ biggpoppa@gmail.com” }

1 个答案:

答案 0 :(得分:0)

没关系,对于遇到同样问题的任何人,在邮递员中您都必须将标题放入Content-Type:application / json。 我输入了Contetn-Type:application / x-www-form-urlencoded加上前面所说的内容