If you have any query feel free to chat us!
Happy Coding! Happy Learning!
When a user submits a form in HTML, the form data is sent to the server as a series of key-value pairs. In order to access this form data on the server, we need to use a middleware called body-parser
.
body-parser
parses the request body and populates the req.body
object with the parsed data.
Here is an example of how to use body-parser
to parse form data:
javascriptCopy code
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.post('/contact', (req, res) => {
const name = req.body.name;
const email = req.body.email;
const message = req.body.message;
// Do something with the data, such as saving it to a database
res.send('Thanks for your message!');
});
app.listen(3000, () => console.log('Server listening on port 3000'));
In the above example, we are using two types of body-parser
middleware to parse form data: urlencoded
and json
. urlencoded
is used for parsing data in application/x-www-form-urlencoded
format, which is the default format used by HTML forms. json
is used for parsing data in application/json
format, which is used by many APIs.
After parsing the form data, we can access the values of the form fields using req.body
. In the example, we are storing the values of the name
, email
, and message
fields in variables, but you can do whatever you like with the data.
Finally, we send a response back to the client using res.send()
. In this case, we are sending a simple "Thanks for your message!" message, but you could send anything you like.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.