I am new to node.js and facing some errors. I am trying to send a POST request on Postman but it's giving me blank with no data in it. And also I checked if my data is valid or not then I got, the data I am sending is valid. Can anyone suggest me?
This is my index File(index.js):
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
//Import Routes
const authRoute = require("./routes/auth");
const postRoute = require("./routes/posts");
dotenv.config();
//connect to DB
mongoose.connect(
process.env.DB_CONNECT,
{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true },
() => console.log("connected to DB!!")
);
//Middleware
app.use(express.json());
//Route Middlewares
app.use("/api/user", authRoute);
app.use("/api/posts", postRoute);
//PORT NUMBER
const port = process.env.PORT || 8080; // default port to listen
// start the Express server
app.listen(port, () => {
console.log(`server started at http://localhost:${port}`);
});
This is my Auth file(auth.js):
const router = require("express").Router();
const User = require("../model/User");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const { registerValidation, loginValidation } = require("../validation");
//REGISTER
router.post("/register", async (req, res) => {
console.log("register");
//Lets validate a data before we make a user
const { error } = registerValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//Checking if the user is already in the database
const emailExist = await User.findOne({ email: req.body.email });
if (emailExist) return res.status(400).send("Email Already Exists");
//HASH THE PASSWORD
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
//Create a New User
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword,
});
try {
const savedUser = await user.save();
res.send({ user: user._id });
} catch (err) {
res.status(400).send(err);
}
});
//LOGIN
router.post("/login", async (req, res) => {
//Lets validate a data before we make a user
const { error } = loginValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//Checking if the email exists in the database
const user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Email is Not Found");
//Check if password is correct
const validPass = await bcrypt.compare(req.body.password, user.password);
if (!validPass) return res.status(400).send("Invalid Password");
//Create and assign a Token
const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
res.header("auth-token", token).send(token);
});
module.exports = router;
As you can see:
I am not able to send data and fetch it with the POST request, DB is connected too.
Try console.log(req.body)
. If your req.body
is empty then you need to add a package body-parser
in middleware(index.js file).
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.