码迷,mamicode.com
首页 > 其他好文 > 详细

Defining RESTful Routes(CRUD operations)

时间:2021-02-09 11:57:54      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:rect   lazy   url   ams   for   ima   thinking   tail   nic   

refer to : https://www.udemy.com/course/the-web-developer-bootcamp/

Get VS Post Requests

Get:

    • Used to retrive information
    • Data is sent via query string
    • information is plainly visible in the URL
    • Limited amount of data can be sent

Post:

    • Used to post data to the server
    • Used to write/create/update
    • Data is sent via request body, not a query string!
    • can send any sort of data(JSON)

 

REST is an architectural style for distributed hypermedia systems.

It‘s basically a set of guidenlines for how a client + server should communicate and perform CRUD operations on  a given resource.

URL定位资源,用HTTP动词(GET,POST,DELETE,DETC)描述操作。

技术图片

技术图片

需要提前install的东西:

npm -i init -y

npm -i express

npm -i uuid. //产生随机的独一无二的id

npm install method-override

npm -i nodemon

nodemon index.js

技术图片

index.js

const path = require(‘path‘); const methodOverride = require(‘method-override‘) const { v4: uuid } = require(‘uuid‘); //For generating ID‘s const express = require(‘express‘); const app = express(); //To parse form data in POST request body: app.use(express.urlencoded({ extended: true })) // To parse incoming JSON in POST request body: app.use(express.json()) // To ‘fake‘ put/patch/delete requests: app.use(methodOverride(‘_method‘)) // Views folder and EJS setup: app.set(‘views‘, path.join(__dirname, ‘views‘)) app.set(‘view engine‘, ‘ejs‘) // Our fake database: let comments = [ { id: uuid(), username: ‘Todd‘, comment: ‘lol that is so funny!‘ }, { id: uuid(), username: ‘Skyler‘, comment: ‘I like to go birdwatching with my dog‘ }, { id: uuid(), username: ‘Sk8erBoi‘, comment: ‘Plz delete your account, Todd‘ }, { id: uuid(), username: ‘onlysayswoof‘, comment: ‘woof woof woof‘ } ] // ********************************** // INDEX - renders multiple comments // ********************************** app.get(‘/comments‘, (req, res) => { res.render(‘comments/index‘, { comments }); }) // ********************************** // NEW - renders a form // ********************************** app.get(‘/comments/new‘, (req, res) => { res.render(‘comments/new‘); }) // ********************************** // CREATE - creates a new comment // ********************************** app.post(‘/comments‘, (req, res) => { const { username, comment } = req.body; comments.push({ username, comment, id: uuid() }) res.redirect(‘/comments‘); }) // ******************************************* // SHOW - details about one particular comment // ******************************************* app.get(‘/comments/:id‘, (req, res) => { const { id } = req.params; const comment = comments.find(c => c.id === id); res.render(‘comments/show‘, { comment }) }) // ******************************************* // EDIT - renders a form to edit a comment // ******************************************* app.get(‘/comments/:id/edit‘, (req, res) => { const { id } = req.params; const comment = comments.find(c => c.id === id); res.render(‘comments/edit‘, { comment }) }) // ******************************************* // UPDATE - updates a particular comment // ******************************************* app.patch(‘/comments/:id‘, (req, res) => { const { id } = req.params; const foundComment = comments.find(c => c.id === id); //get new text from req.body const newCommentText = req.body.comment; //update the comment with the data from req.body: foundComment.comment = newCommentText; //redirect back to index (or wherever you want) res.redirect(‘/comments‘) }) // ******************************************* // DELETE/DESTROY- removes a single comment // ******************************************* app.delete(‘/comments/:id‘, (req, res) => { const { id } = req.params;
//怎么删除?把不是选定的id的过滤出来,放在一个新的数组里面存起来然后显示 comments
= comments.filter(c => c.id !== id); res.redirect(‘/comments‘); }) app.get(‘/tacos‘, (req, res) => { res.send("GET /tacos response") }) app.post(‘/tacos‘, (req, res) => { const { meat, qty } = req.body; res.send(`OK, here are your ${qty} ${meat} tacos`) }) app.listen(3000, () => { console.log("ON PORT 3000!") }) // GET /comments - list all comments // POST /comments - Create a new comment // GET /comments/:id - Get one comment (using ID) // PATCH /comments/:id - Update one comment // DELETE /comments/:id - Destroy one comment
edit.ejs

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit</title>
</head>

<body>
    <h1>Edit</h1>
//sending a post request, but thinking it as a patch request, use method-override <form method="POST" action="/comments/<%=comment.id%>?_method=PATCH"> <textarea name="comment" id="" cols="30" rows="10"><%= comment.comment %></textarea> <button>Save</button> </form> </body> </html>
index.ejs

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comments Index</title>
</head>

<body>
    <h1>Comments</h1>
    <ul>
        <% for(let c of comments) {%>
        <li>
            <%=c.comment%> - <b><%=c.username%></b>
            <a href="/comments/<%= c.id %>">details</a>
        </li>
        <% }%>
    </ul>
    <a href="/comments/new">New Comment</a>

</body>

</html>
new.ejs

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New Comment</title> </head> <body> <h1>Make a new comment</h1> <form action="/comments" method="post"> <section> <label for="username">Enter username:</label> <input type="text" id="username" placeholder="username" name="username"> </section> <section> <label for="comment">Comment Text</label> <br> <textarea id="comment" cols="30" rows="5" name="comment"></textarea> </section> <button>Submit</button> </form> <a href="/comments">Back to Index</a> </body> </html>
show.ejs

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Show</title>
</head>

<body>
    <h1>Comment id: <%= comment.id %></h1>
    <h2><%= comment.comment %> - <%=comment.username %></h2>
    <a href="/comments">Back to index</a>
    <a href="/comments/<%= comment.id%>/edit">Edit Comment</a>
    <form method="POST" action="/comments/<%= comment.id %>?_method=DELETE">
        <button>Delete</button>
    </form>
</body>

</html>

 问题:

  • 为什么要用到method_override?
  • // To ‘fake‘ put/patch/delete requests:
    app.use(methodOverride(‘_method‘))

html  forms in our browser can only send a get or a post request. They can not send put requeest or patch request or delete request

  • 怎么生成unique id 

npm -i uuid. -> const { v4: uuid } = require(‘uuid‘);  -> id: uuid() 

效果图:

技术图片

技术图片

技术图片

技术图片

 

Defining RESTful Routes(CRUD operations)

标签:rect   lazy   url   ams   for   ima   thinking   tail   nic   

原文地址:https://www.cnblogs.com/LilyLiya/p/14383631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!