Share
Explore

Node Express Server and Forms

write the code for an Node.js Express Web Server with HTML forms and a program to access the form field data:

This code creates a server using the Express.js framework. It listens for GET requests to the root '/' route, and sends a form for the user to fill out.

When the form is submitted, the form data is sent to the server as a POST request to the '/contact' route. The body-parser middleware is used to parse the form data, which is then logged to the console and returned to the user as a response.


const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.send(`
<form action="/contact" method="POST">
<input type="text" name="name" placeholder="Name" />
<input type="email" name="email" placeholder="Email" />
<input type="submit" value="Submit" />
</form>
`);
});

app.post('/contact', (req, res) => {
const name = req.body.name;
const email = req.body.email;

console.log(name, email);
res.send(`Thanks for contacting us, ${name}! We'll get back to you at ${email} soon.`);
});
app.listen(3000

Write the NODE.JS code for the program that receives and processes the form fields:

The code provided already receives and processes the form fields.

In the GET request to the root '/' route, it sends a form to the user to fill out.
In the POST request to the '/contact' route, it uses the body-parser middleware to parse the form data and then logs the name and email fields to the console and returns a response to the user.
The code is listening for incoming requests on port 3000 using the app.listen(3000) method.

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.