Parsing Form Data - Storing The Contact

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 261:- Parsing Form Data - Storing The Contact

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.

30. My First Express App - Continued

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support