完整程式碼,請洽: https://github.com/Zrn-code/Node-js-tutorial/tree/node-10
# 新增
create.ejs | <div class="create-blog content"> |
| <form action="/blogs" method="POST"> |
| <label for="title">Blog title:</label> |
| <input type="text" id="title" name="title" required> |
| <label for="snippet">Blog snippet:</label> |
| <input type="text" id="snippet" name="snippet" required> |
| <label for="body">Blog body:</label> |
| <textarea id="body" name="body" required></textarea> |
| <button >Submit</button> |
| </form> |
| </div> |
app.js | app.use(express.urlencoded( { extended: true })); |
| app.post('/blogs',(req,res) => { |
| |
| const blog = new Blog(req.body); |
| blog.save() |
| .then((result)=> res.redirect('/blogs')) |
| .catch(err) => console.log(err); |
| }); |
index.ejs | <div class="blogs content"> |
| <h2>All Blogs</h2> |
| <% if (blogs.length > 0) { %> |
| <% blogs.forEach(blog = >{ %> |
| <a class="single" href="blogs/<%- blog._id %>"> |
| <h3 class= "title"><%= blog.title %></h3> |
| <p class="snippet"><%= blog.snippet %></p> |
| </a> |
| <% }) %> |
| <% } else |