fxndvi
fxndvi

Reputation: 79

How can I receive post data in a node js server with express?

I tried two middlewares but still getting this output in the terminal:

{}

my node js server code:

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

const app = express();

//the middlewares i tried
app.use(express.urlencoded({extended: false}));
app.use(bodyParser());

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/client.html');
});

app.post('/test', (req, res) => {
   res.send('this is a test path');
   console.log(req.body);
});

app.listen(3000, () => {
  console.log('server listening...');
});

my form (client.html file):

<form method="POST" action="/test">
    <input type="text">
    <input type="submit">
</form>

I also tried send the post data with postman. I know that the action in the html form is working because I can see the "this is a test path" output in the browser

Upvotes: 0

Views: 49

Answers (3)

A.kurd
A.kurd

Reputation: 1

you should write code like this

var app=express();
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

app.post('/test', (req, res) => {
   console.log(req.body.email);
   res.send('this is a test path'+req.body.email);

});


Upvotes: 0

fxndvi
fxndvi

Reputation: 79

in fact it works just like

app.use(express.urlencoded());

the wrong thing was the nameless input in the html form

Upvotes: 0

Saurabh Mistry
Saurabh Mistry

Reputation: 13699

try this

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

const app = express();


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


app.get('/', (req, res) => {
    res.sendFile(__dirname + '/client.html');
});

app.post('/test', (req, res) => {
   res.send('this is a test path');
   console.log(req.body);
});

app.listen(3000, () => {
  console.log('server listening...');
});

also in html form , add name property in input tag

<form method="POST" action="/test">
    <input type="text" name="email">
    <input type="submit">
</form>

Upvotes: 1

Related Questions