我的请求正文在节点API中显示为空或未定义

时间:2019-10-08 08:24:22

标签: node.js api express

这是我用来验证我的登录名的API,但未收到正确的请求正文。

这是我与MongoCloud连接的服务器/索引文件。

 const express = require("express");
const mongoose = require("mongoose");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const posts = require("./routes/api/posts");
const app = express();
const bodyParser = require("body-parser");


// DB Config
const db = require("./config/keys").mongoURI;
// Connect Mongo
mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log("Mongo is connected"))
  .catch(err => console.log(err));
// var MongoClient = require("mongodb").MongoClient;


//Enabling body parser
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.get("/", (req, res) => res.send("Hello!"));

app.use("/api/users", users);
app.use("/api/posts", posts);
app.use("/api/profile", profile);

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server is running on port ${port}`));

这是路由文件,其中包含用于注册和登录用户的API。

    const express = require("express");
const router = express.Router();
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");

const User = require("../../models/User");
// @Route GET api/users/test
// desc test users route
// access public
router.get("/test", (req, res) => res.json({ msg: "users works" }));

// @Route POST api/users/register
// desc register a user
// access public
router.post("/register", (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json({ email: "email already exists" });
    } else {
      const avatar = gravatar.url(req.body.email, {
        s: "200", //size
        r: "pg", //rating
        d: "mm" //default
      });

      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      });
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});

// @Route POST api/users/login
// desc Login User/Returning JWT(json web token)
// access public

router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  //Find user by email

  User.findOne({ email }).then(user => {
    if (!user) {
      return res.status(404).json({ email: "user not found" });
    } else {
      //Check Password
      bcrypt.compare(password, user.password).then(isMatch => {
        if (isMatch) {
          res.json({ msg: "Success" });
        } else {
          return res.status(400).json({ password: "Incorrect Password" });
        }
      });
    }
  });
});

module.exports = router;

我正在编写一种类似的API来注册我的用户,效果很好。

1 个答案:

答案 0 :(得分:1)

我认为您需要导出路由文件,并像下面那样在index.js中使用它。

index.js

const express = require("express");
const app = express();
const authRoute = require("./authRoute");

app.use(express.json());

app.use("/auth", authRoute);

const port = process.env.PORT || 3000;
app.listen(port, () => console.log("Listening"));

还有您的路由文件,我叫authRoute.js。

const express = require("express");
const router = express.Router();

router.post("/login", async (req, res) => {
  console.log(req.body);
  res.send(req.body);
});

module.exports = router;

如果您向端点/ auth / login发送发帖请求,则可以阅读req.body。例如,如果使用localhost:3000:

http://localhost:3000/auth/login