置頂
一個不錯的測試視頻:https://www.imooc.com/learn/1048
一、模擬服務器接口
https://github.com/typicode/json-server
這個工具叫做 json-server
二、模擬數據
隨便寫一個json數據,起名為 db.json。
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
三、啟動服務器
在 db.json 的目錄下啟動命令行工具,輸入指令:
json-server --watch db.json
如果沒報錯就算成功了。
按照提示,訪問 http://localhost:3000/posts 就能看到 db.json 中的 posts 字段下的數據;
同理,如果訪問 http://localhost:3000/comments 就能看到 db.json 中的 comments 字段下的數據;
如果訪問 http://localhost:3000/profile 就能看到 db.json 中的 profile 字段下的數據。
四、Postman 的下載安裝
1. 下載安裝 Postman( windows 64 位)
https://dl.pstmn.io/download/latest/win64
2. 注冊賬號並登錄
用自己的郵箱注冊一個,很方便。
五、Postman 的基本使用
登錄進去,出現主頁面。
(1) 找到搜索框下的 Collection,這里可以創建不同的文件夾,方便以后測試接口。
(2) 點擊 New Collection,新建一個文件夾。
(3) 右擊剛剛創建的 test 文件夾,添加一個請求。
(4) GET 方法
GET 方法用來查詢數據,查找字段 posts 下的所有數據。(GET /posts)
如果查詢 posts 下的第一條數據:/posts/1 (這個 1 是由數據中的 id 決定的。)
(5) POST 方法
POST 方法用來添加新數據,給 posts 下添加一條新數據。(POST /posts)
POST 方法上傳的數據在 Body 中配置,選擇第三個 x-www-form-urlencoded,將參數的鍵值分別寫在 key 和 vlaue 中。
注意:id 不用配置進去,它會自動依次添加。
(6) PUT 方法
PUT 方法用來修改數據,修改 posts 下 id 為 2 的數據。(PUT /posts/2)
Body > x-www-form-urlencoded > data
(7) DELETE 方法
DELETE 方法用來刪除數據,刪除 posts 下 id 為 2 的數據。(DELETE /posts/2)
五、總結
- 創建文件夾便於分類
- 熟悉GET、POST、PUT、DELETE這些請求方法。
- 其中 POST 方法不可以直接上傳到某一條具體的數據位置,POST /posts/1 會 404。