If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To create a new post, you need to create a form to send the data to the server. Here are the steps to do it:
views
folder, create a new file called new.ejs
. This file will contain the form to create a new post.new.ejs
file, create a form element with the following attributes:htmlCopy code
<form method="POST" action="/posts">
</form>
This form will send a POST request to the /posts
route when the user submits it.
htmlCopy code
<form method="POST" action="/posts">
<div>
<label for="title">Title</label>
<input type="text" id="title" name="title" required>
</div>
<div>
<label for="body">Body</label>
<textarea id="body" name="body" rows="10" required></textarea>
</div>
<button type="submit">Create Post</button>
</form>
This form has two input fields: a text field for the title of the post, and a textarea for the body of the post. The name
attribute of each input field corresponds to the property of the post object in the database.
routes/posts.js
file, add a new route to handle the POST request from the form:javascriptCopy code
router.post('/', isLoggedIn, async (req, res) => {
// create a new post using the data from the form
const post = new Post({
title: req.body.title,
body: req.body.body,
author: req.user._id
});
// save the new post to the database
await post.save();
// redirect to the home page
req.flash('success', 'Post created successfully!');
res.redirect('/');
});
This route uses the Post
model to create a new post object using the data from the form. The author
property is set to the ID of the currently logged-in user. The new post is saved to the database using the save()
method, which is an asynchronous operation. Once the post is saved, the user is redirected to the home page, and a success flash message is displayed.
app.js
file, add the body-parser
middleware to parse the data from the form:javascriptCopy code
const bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
This middleware parses the request body and makes it available in the req.body
object.
With these steps, you have created a form to create a new post and handled the POST request to save the post to the database.
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.