Json-server總結
阿新 • • 發佈:2022-02-27
一、什麼是JSON-Server?
JSON-Server 是一個 Node 模組,執行 Express 伺服器,可以指定一個 json 檔案作為 api 的資料來源。
二、JSON-Server的使用
全域性安裝:
cmd命令列視窗輸入:
npm install -g json-server
使用:
首先準備一個json檔案:test.json
格式如下:
{ "posts": [ { "id": 1, "title": "1111-修改-11111", "author": "kk" }, { "id": 2, "title": "22222", "author": "tiechui" }, { "title": "33333", "author": "xiaoming", "id": 3 } ], "comments": [ { "id": 1, "body": "11111-comment", "postId": 1 }, { "id": 2, "body": "22222-comment", "postId": 2 } ] }
然後使用全域性json-server命令,啟動mock服務。
json-server --watch --port 8000 test.json
輸出如下內容說明啟動成功。
資料訪問舉例(增刪改查)
import React from 'react' import { Button } from 'antd'; // import axios from 'axios' export default function Home() { const ajax = ()=>{ //取資料 get // axios.get("http://localhost:8000/posts/2").then(res=>{ // console.log(res.data) // }) // 增 post // axios.post("http://localhost:8000/posts",{ // title:"33333", // author:"xiaoming" // }) // 更新 put // axios.put("http://localhost:8000/posts/1",{ // title:"1111-修改" // }) // 更新 patch // axios.patch("http://localhost:8000/posts/1",{ // title:"1111-修改-11111" // }) // 刪除 delete // axios.delete("http://localhost:8000/posts/1") // _embed,取關聯陣列,向下 // axios.get("http://localhost:8000/posts?_embed=comments").then(res=>{ // console.log(res.data) // }) // _expand,向上關聯 // axios.get("http://localhost:8000/comments?_expand=post").then(res=>{ // console.log(res.data) // }) } return ( <div> <Button type="primary" onClick={ajax}>Button</Button> </div> ) }