NODEJS POST METHOD

POST METHOD

Program 1:

  • FILE NAME        : Index.html 
  • FOLDER NAME : Project folder

 Index.html

<!DOCTYPE html>

<html>

<head>

<title>Simple Form</title>

</head>

<body>

<h1>Simple Form</h1>

<form action="/submit" method="post">

<label for="name">Name:</label>

<input type="text" id="name" name="name"

required><br><br>

<label for="age">Age:</label>

<input type="number" id="age" name="age"

required><br><br>

<input type="submit" value="Submit">

</form>

</body>

</html>



Program 2:

  • FILE NAME        : Index.js 
  • FOLDER NAME : Project folder


const express = require('express');

const app = express();

const port = 3000;


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

app.use(express.static('public'));


app.post('/', (req, res) => {

res.sendFile(__dirname + '/public/index.html');

});


app.post('/submit', (req, res) => {

const name = req.body.name;

const age = req.body.age;

res.send(`Name: ${name}, Age: ${age}`);

});


app.listen(port, () => {

console.log(`Server is running on port ${port}`);

});


Note:

 Put html file inside public folder(public folder created

manually)

 Js file @ main project folder

No comments:

Post a Comment