Express Post form Data – d

In this example we use POST method to pass data from client to server. POST is frequently used for FORM submissions.

First we create our project run npm init and name project as postdata and create file called app.js in our project and add the following code in app.js

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

const app = express();

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

// Set Static path
app.use(express.static(path.join(__dirname, 'public')));

app.post('/student', (req, res) => {
  let name = req.body.firstName + ' ' + req.body.lastName;
  let email = req.body.email;

  res.send('Student name : ' + name + '<br/>' + 'Student email :' + email);
});

app.listen(3000, () => {
  console.log('Server started on port 3000...');
});

We are using expressjs and body-parse, in command line install both package as
$ npm install express –save
$ npm i body-parser –save

Create a folder public in our root folder and create index.html add the following code, so we can add form data in index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Express Post</title>
</head>

<body>
  <div class="conatiner">
    <h2>Post Form data in Express Nodejs</h2>

    <form method="post" action="/student">
      First name:<br/>
      <input type="text" name="firstName" placeholder="First name">
      <br/><br/>
      Last name:<br/>
      <input type="text" name="lastName" placeholder="Last name">
      <br><br>
      Email:<br>
      <input type="text" name="email" placeholder="Email">
      <br/><br/>
      <input type="submit" value="Submit">
    </form> 
  </div>
</body>
</html>
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top