Chapter 7 json-server and axios
Start a project from the project, generally simultaneously front and rear ends of the coding, and at this time the front end of the interface and background data required are not available;
7.1 json-server use
Use global installation:npm install json-server -g
json-server will json file as a database to store data, data format json is required, such as data.json content:
{
"tb1": [
{
"id": 1,
"title": "标题1",
"author": "描述信息1"
},
{
"id": 2,
"title": "标题2",
"author": "描述信息2"
}
],
"tb2": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"tb3": {
"name": "typicode"
}
}
Start the service: json-server --watch data.json
After a successful start, prompt information is as follows:
$ json-server --watch data.json
\{^_^}/ hi!
Loading data.json
Done
Resources
http://localhost:3000/tb1
http://localhost:3000/tb2
http://localhost:3000/tb3
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
Tb1 get all the data GET: http: // localhost: 3000 / tb1
http:: // localhost: id GET data obtained in accordance with 3000 / tb1 / 2
Adding a data POST: http: // localhost: 3000 / tb1
To delete a data DELETE: http: // localhost: 3000 / tb1 / 2
Fuzzy Lookup GET: http: // localhost: 3000 / tb1 title_like = title?
The modification data id PUT: http: // localhost: 3000 / tb1 / 1
Note: json-server semantics strictly follow the HTTP request for data processing
7.2 axios
We need to access an API when building applications and present their data. There are ways to do this are several, but based Promise HTTP client axios is one of a very popular one.
<script src="./axios.js"></script>
<script>
// 获取全部数据
axios.get('http://localhost:3000/list_data')
.then((data)=>{
console.log(data);
});
// 获取一条数据
axios.get('http://localhost:3000/list_data/2')
.then((data)=>{
console.log(data);
})
// 添加一条数据
axios.post('http://localhost:3000/list_data',{stat:false,title:'喝水'})
.then((d)=>{
console.log(d);
}).catch(error => console.log(error))
// 删除一条数据
axios.delete('http://localhost:3000/list_data/4')
.then((d)=>{
console.log(d);
}).catch(error => console.log(error))
// 修改一条数据
axios.put('http://localhost:3000/list_data/6',{title:'hhhhhh'})
.then((d)=>{
console.log(d);
}).catch(error => console.log(error))
</script>