Home > Enterprise >  node.js express req.body undefined
node.js express req.body undefined

Time:04-28

var express = require('express'); 
var app = express(); 
var PORT = 3000; 

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));
 
app.post('/', function (req, res) { 
  console.log(req.body); 
  console.log(req.body.username);
  res.end(); 
}); 

app.listen(PORT, function(err){ 
  if (err) console.log(err); 
  console.log("Server listening on PORT", PORT); 
});

Test by postman: Post: http://localhost:3000 { "username":"userabc", "password":"passwd1234" }

But, the result is: {} undefined

CodePudding user response:

Try setting Content-Type: application/json in the request body

CodePudding user response:

You need to set Content-Type as application/json on the request.

CodePudding user response:

The way you have written code is very optimistic way and could lead to errors if someone doesn't provide the body, put some validations in the apis I am sharing some code snippet which I used in one of my project as it would help you better understand things.

Please take the code as reference implementation only. This is the router part of the code you will need to import it in your app.js or index.js module

import express from "express";

import { Request, Response } from "express";
import { body, validationResult } from "express-validator";
import { BadRequestError } from "@omerkiani/common";
import { RequestValidationError } from "@omerkiani/common";
import { User } from "../models/user";
import { validateRequest } from "@omerkiani/common";
import { Password } from "../services/password";
import jwt from "jsonwebtoken";
import { requireAuth } from "@omerkiani/common";
import { currentUser } from "@omerkiani/common";

const router = express.Router();


router.post(
  "/api/users/signup",
  [
    body("email").isEmail().withMessage("Email must be valid"),
    body("password")
      .trim()
      .isLength({ min: 4, max: 20 })
      .withMessage("Password must be between 4 and 20 characters"),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      throw new RequestValidationError(errors.array());
    }
    console.log("Creating a user...");
    const { email, password } = req.body;
    const exiting = await User.findOne({ email });
    if (exiting) {
      console.log("Email already in use");
      throw new BadRequestError("Email already in use");
    }


    const user = User.build({ email, password });
    await user.save();


    //Generate Json Web Token
    const userJwt = jwt.sign({ id: user.id, email: user.email }, process.env.JWT_KEY!);
    req.session = {jwt: userJwt};
    //End


    res.status(201).send(user);
  }
);

router.post(
  '/api/users/signin',
  [
    body('email')
      .isEmail()
      .withMessage('Email must be valid'),
    body('password')
      .trim()
      .notEmpty()
      .withMessage('You must supply a password')
  ],
  validateRequest,
  async (req: Request, res: Response) => {
    const { email, password } = req.body;

    const existingUser = await User.findOne({ email });
    if (!existingUser) {
      throw new BadRequestError('Invalid credentials');
    }

    const passwordsMatch = await Password.compare(
      existingUser.password,
      password
    );
    if (!passwordsMatch) {
      throw new BadRequestError('Invalid Credentials');
    }

    // Generate JWT
    const userJwt = jwt.sign(
      {
        id: existingUser.id,
        email: existingUser.email
      },
      process.env.JWT_KEY!
    );

    // Store it on session object
    req.session = {
      jwt: userJwt
    };

    res.status(200).send(existingUser);
  }
);

router.post('/api/users/signout', (req, res) => {
  req.session = null;

  res.send({});
});


router.get('/api/users/currentuser', currentUser, (req, res) => {
  res.send({ currentUser: req.currentUser || null });
});


export { router as AuthRouter };

The index.js file looks like this

import express from "express";
import cookieSession from 'cookie-session';
import "express-async-errors";
import { AuthRouter } from "./routes/auth_router";
import { errorHandler } from "@omerkiani/common";
import { NotFoundError } from "@omerkiani/common";

import mongoose from "mongoose";
const app = express();
app.set('trust proxy', true);
app.use(express.json());
app.use(cookieSession({
  signed: false,
  secure: true
}));

app.use(AuthRouter);
app.use(errorHandler);


app.all("*", async (req, res) => {
  throw new NotFoundError();
});

const start = async () => {

  if (!process.env.JWT_KEY) {
    throw new Error("JWT Key Should be Defined");
  }

  if (!process.env.MONGO_URI) {
    throw new Error("Mongo URI Should be Defined");
  }

  try {
    await mongoose.connect(process.env.MONGO_URI!, {});
    console.log("Connected to MongoDB");
  } catch (err) {
    console.error(err);
  }
};


app.listen(3000, () => {
  console.log("Auth Up on Port 3000!");
});

start();

CodePudding user response:

How did you set up your Postman body request?

  • Related