通過下面這篇文章我們來了解什么是JSON-server, 如何利用它來做一些臨時(shí)JSON數(shù)據(jù)。
1. 什么是JSON-server
簡(jiǎn)單來說就是把JSON文件當(dāng)作一個(gè)臨時(shí)的數(shù)據(jù)庫使用的這樣一個(gè)工具孤钦。你可以對(duì)其做get, post請(qǐng)求。比如說你想用本地JSON文件來做個(gè)數(shù)據(jù)源弟翘,然后用JSON-server來觀察管理這個(gè)文件粘衬,要給這個(gè)JSON文件做API請(qǐng)求接口端口的話,利用JSON-server我們就可以跟這個(gè)本地JSON文件做交互新娜。
例如桅滋,下面的這個(gè)blog.JSON文件結(jié)構(gòu)是這樣的:
{
"blogs":[
{id:1, title:"this is blog title 1"},
{id:2, title:"this is blog title 2"},
{id:3, title:"this is blog title 3"},
]
}
如果我們對(duì)其加入API請(qǐng)求端口的話:
[http://localhost:3000/blogs](http://localhost:3000/blogs) -->get請(qǐng)求博客列表
[http://localhost:3000/blogs](http://localhost:3000/blogs) --> post請(qǐng)求添加新博客
[http://localhost:3000/blogs](http://localhost:3000/blogs)/id --> 獲取單個(gè)博文的請(qǐng)求
[http://localhost:3000/blogs](http://localhost:3000/blogs)/id --> 刪除單個(gè)博文的請(qǐng)求
這樣我們就可以做一個(gè)本地的API接口來進(jìn)行測(cè)試了慧耍。
2. 如何安裝JSON-SERVER
你的本地環(huán)境需要安裝nodejs, 這樣我們就可以用NPM來安裝這個(gè)插件了。
npm install -g json-server
安裝以后查看下package.json文件里面是不是有這個(gè)依賴了丐谋。
3.用JSON-server來觀察文件
這個(gè)比較簡(jiǎn)單芍碧,我們可以直接運(yùn)行下面的命令:
json-server --watch blog.json
回車以后我們就會(huì)看見兩個(gè)端口:
http://localhost:3000/blogs
http://localhost:3000
blogs這個(gè)URL是根據(jù)文件里的"blogs"這個(gè)對(duì)象數(shù)組來生成的,如果加入了另一個(gè)數(shù)組号俐,如:
"articles":[], 那么我們就會(huì)看到多了另外一個(gè)端口:
http://localhost:3000/artciles
如果你是在windows系統(tǒng)泌豆,在運(yùn)行的時(shí)候可能會(huì)遇到這種錯(cuò)誤:
如何解決呢?運(yùn)行下這個(gè)命令:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
4.post請(qǐng)求示例
我們可以對(duì)其進(jìn)行post請(qǐng)求吏饿,在HTML里面做一個(gè)提交表踪危,下面是一個(gè)用fetch來做POST請(qǐng)求的例子:
const url = "http://localhost:3000/blogs";
const form = document.querySelector("form");
const createPosts = async (e) => {
e.prevenDeault();
const doc = {
title:form.title.value,
content:form.title.value
}
await fetch(url, {
method:"post",
body:JSON.stringify(doc),
headers:{
'content-type':'application/json'
}
})
}
form.addEventListener('submit', createPosts);
一般的數(shù)據(jù)表里面都有id這個(gè)字段,它也會(huì)自動(dòng)進(jìn)行自增的處理猪落,不用傳入贞远。
5. delete請(qǐng)求示例
delte請(qǐng)求跟post請(qǐng)求比較類似,就是把post換成delete便可笨忌。
deletebtn = document.addEventListener('.deletebtn');
let id = new URLSearchParams(window.location.search).get('id');
//獲取URL 參數(shù)
deletebtn.addEventListener('click', async () => {
await fetch(url+id, {
method:"DELETE"
})
})
6.搜索和排序
搜索的時(shí)候非常簡(jiǎn)單蓝仲,在URL里面加一個(gè)搜索參數(shù)q就可以了。例如:
http://localhost:3000/blogs?q=searchterm
它會(huì)在title和content里面搜索這個(gè)關(guān)鍵詞
我們可以用某個(gè)字段來排序官疲,例如用升序來排博文袱结,也就是ID字段
http://localhost:3000/blogs?_sort=id&_order=desc