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

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

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

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?