manikandan
manikandan

Reputation: 805

Post method values returned null in node js

When submit the form the form fields value not came in post method.

here is code in index.html file

<form method="POST" action="http://localhost:4000/insertion">
    <div class="form-group">
        <label>E-Mail</label>
        <input type="text" name="email" class="form-control" >
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" name="password" class="form-control" >
    </div>
    <div class="form-group">
        <label>&nbsp;</label>
        <input type="submit" name="submit" class="btn btn-primary" value="Submit">
    </div>
</form>

in server side script code is

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

var app = express();

app.use(bodyParser.json())

app.use(cors());

app.post('/insertion',function(request,response){
    console.log(request.body);
});

app.get('/index',function(request,response){
    response.send('hi ');
});

app.listen(4000);

its not showing showing any error but value is empty

Upvotes: 0

Views: 989

Answers (3)

manikandan
manikandan

Reputation: 805

follow this... need to pass value in url function

var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.post('/formdata',urlencodedParser,function(req,res){
    console.log(req.body);
});

Upvotes: 0

Naren
Naren

Reputation: 4470

You need use bodyParser.urlencoded to read the form data.

Add this and try again.

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

Upvotes: 1

Samuel Chibuike
Samuel Chibuike

Reputation: 166

You need to add app.use(bodyParser.urlencoded({extended: false})) after the app.use(bodyParser.json()). You can see documentation here

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

var app = express();

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

app.use(cors());

app.post('/insertion',function(request,response){
    console.log(request.body);
});

app.get('/index',function(request,response){
    response.send('hi ');
});

app.listen(4000);

Upvotes: 0

Related Questions