2

Hello guys i searched a lot about it and tried everything but still I get empty body in post (The form sends body correct I just test with fiddler the node express is not getting that)!

Here is the code :

This is my Form

<form action="/user/login" method="POST">
                        <div class="form-group">
                            <label class="form-control-label">USERNAME</label>
                            <input type="text" class="form-control" name="username">
                        </div>
                        <div class="form-group">
                            <label class="form-control-label">PASSWORD</label>
                            <input type="password" class="form-control" name="password">
                        </div>

                        <div class="col-lg-12 loginbttm d-flex">
                            <div class="col-lg-6 login-btm login-text">
                                <p id="loginError" class="text-danger"></p>
                            </div>
                            <div class="col-lg-6 login-btm login-button">
                                <button type="submit" class="btn btn-outline-primary" id="loginBtn">LOGIN</button>
                            </div>
                        </div>
                    </form>

And this is my router and express codes:

app.use(express.json());
app.use(express.urlencoded({extended:true}));
const {loginRouter,loginRouterP} = require('./src/routes/login');
app.use('/login', loginRouter);
app.use('/user/login', loginRouterP);

And this is login Routers in other folder which I get body null:

loginRouter.get('',async(req,res) => {
res.render('login');
});
loginRouterP.post('',async(req,res) => {
console.log(req.body); // This is always {} i tried almost everything I found in stackoverflow
});

EDIT: Sorry the enctype was there by mistake I was just trying to fix

Mobinkh
  • 117
  • 1
  • 7
  • open your browser console, see what kind of `Content-type` header is being sent by the browser, if it's something like `multipart/form-data` you might need additional packages like multer – Dhiraj Jun 14 '21 at 14:54
  • change ```multipart/form-data``` with ```application/x-www-form-urlencoded``` or remove ```enctype="multipart/form-data"```(default value i.e second option will be taken) if you are not dealing with any files. – Muhammad Saquib Shaikh Jun 14 '21 at 15:02

1 Answers1

2

I am assuming you need an additional middleware to accept a plain/text format

app.use(express.json());
app.use(express.text()) // this is for plan/text format
app.use(express.urlencoded({extended: true})); //Parse URL-encoded bodies 

If you are dealing with multipart/form-data you might need packages like multer

Dhiraj
  • 2,687
  • 2
  • 10
  • 34