配置json-server

1.全局安裝json-server【可能須要管理員權限】javascript

npm i -g json-serverjava

2.建立文件夾jsonerver,初始化package.json文件
npm init npm

3.局部安裝json-server
npm i json-server --savejson

4.修改package.json文件,配置啓動方式
"scripts":{
"json:server":"json-server --watch db.json"
}app

5.建立db.json文件jsonp

{
	"users":[
		{
			"name":"zs",
			"phone":"123",
			"email":"zs@qq.com",
			"id":1,
			"age":12,
			"companyId":1           // 這個companyId 使用駝峯命名的,否則是查詢不到的
		},
		{
			"name":"ls",
			"phone":"234",
			"email":"ls@qq.com",
			"id":2,
			"age":13,
			"companyId":2
		},
		{
			"name":"ww",
			"phone":"345",
			"email":"ww@qq.com",
			"id":3,
			"age":14,
			"companyId":3
		},
		{
			"name":"cl",
			"phone":"456",
			"email":"cl@qq.com",
			"id":4,
			"age":15,
			"companyId":3
		}
	],
	"companies":[
		{
			"id":1,
			"name":"Apple",
			"des":"apple is good"
		},
		{
			"id":2,
			"name":"ms",
			"des":"ms is good"
		},
		{
			"id":3,
			"name":"gg",
			"des":"gg is good"
		}
	]
}

  


6.運行
npm run json:serverspa

localhost:3000/xxx
只能運行一個3000的端口,若是含有另外一個3000端口,會運行不成功code

 

7.運行後,能夠查詢以下信息server

//獲取全部用戶信息
http://localhost:3000/users

//獲取id爲1的用戶信息
http://localhost:3000/users/1

//獲取全部公司的信息
http://localhost:3000/companies

//獲取id爲1的公司信息
http://localhost:3000/companies/1

//獲取id爲3的公司的全部用戶
http://localhost:3000/companies/3/users

//獲取名字爲ms的公司
http://localhost:3000/companies?name=ms

//獲取名字爲ms和gg的公司
http://localhost:3000/companies?name=ms&name=gg

//一頁顯示兩條數據
http://localhost:3000/companies?_page=1&_limit=2

//根據公司id的降序排序(desc 降序,asc 升序)
http://localhost:3000/companies?_sort=id&_order=desc

//獲取年齡大於25的用戶
http://localhost:3000/users?age_gte=25

//獲取年齡小於20的用戶
http://localhost:3000/users?age_lte=20

//獲取年齡15到30的用戶
http://localhost:3000/users?age_lte=30&age_gte=15

//搜索用戶信息 q=s 搜索用戶信息中含有s字符串的信息
http://localhost:3000/users?q=s
 
8.經過json-server,把jsonplacehoder的數據,提取到本地
在package.json文件中,配置
 "scripts": {
    "json:server": "json-server --watch db.json",
    "json:server:remote": "json-server http://jsonplaceholder.typicode.com/db"     //添加這行
  },

  從新運行,npm run json:server:remote,能夠訪問到jsonplaceholder中的數據blog

相關文章
相關標籤/搜索