Ben
Ben

Reputation: 57

Req.body IS Populated, But Req.body.user and Req.body.pass isn't

I'm working on doing Auth from scratch. I have ran into a problem when running a post request to my api. If I use postman and populate the form-data section, and post, nothing is in req.body.user and req.body.pass. But, of course, req.body is populated and I can see the form data I've sent. Here's my code:

const express = require("express"),
  app = express(),
  shajs = require("sha.js"),
  bodyParser = require("body-parser"),
  mongoose = require("mongoose"),
  Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost:27017/auth', {useNewUrlParser: true});

app.use(bodyParser.urlencoded({ extended: true }));

let userSchema = new Schema({
  username: String,
  password: String
});

let user = mongoose.model("user",userSchema);

app.post("/user/register",(req,res)=>{
  console.log(req.body);
  let hashedPass = shajs("sha256").update(req.body.pass).digest("hex");
  let newUser = new user({
    username: req.body.user,
    password: hashedPass
  });
});

app.listen(3000,(err,suc)=>{
  if(err){
    console.log(err);
  } else {
    console.log("Yay! The app is up on localhost:3000.");
  }
});

Here's what my req.body looks like:

 { '------WebKitFormBoundaryBZtUrMPzNKlsGLwj\r\nContent-Disposition: form-data; name':
   '"user"\r\n\r\nBlakskyben\r\n------WebKitFormBoundaryBZtUrMPzNKlsGLwj\r\nContent-Disposition: form-data; name="pass"\r\n\r\nBENNNN\r\n------WebKitFormBoundaryBZtUrMPzNKlsGLwj--\r\n' }

Thanks, Ben!

Upvotes: 0

Views: 155

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

bodyParser doesn't handle form-data. You will need to use multer for that.

Otherwise use application/x-www-form-urlencoded since you already have:

app.use(bodyParser.urlencoded({ extended: true }));

In Postman, instead of using the form-data radio, use the x-www-form-urlencoded one.

enter image description here

Upvotes: 1

Related Questions