Introduction to the
Json-server can create a RESTFUL FAKE API in 30 seconds without writing a line of code, with an average of over 150K downloads per week
Why would you use
- Mocks are fast and claim to be able to complete basic mock data mocks in 30 seconds
- Real data data increase, delete, change and check
- Use relatively simple, just need to build a json file to add a resource array of the API you want to achieve the basic add, delete, change, check
- An interface can be defined restful to standardize the interface
- Many mock data platforms are either too difficult to use or too cumbersome to use
Installation and use
- The installation
yarn add -g json-server
Copy the code
- Create a __json_server_mock__ directory in the root directory and create a new db.json file
- Create an API
/ / db. Json {" users ": [{" id" : 1, "name" : "Gao Xiuwen"}, {" id ": 2," name ":" Xiong Tiancheng "}, {" id ": 3," name ":" yeeli hua zheng "}, {" id ": 4, "name": "wang Wenjing"}]}Copy the code
- Add the startup command to pack.json json-server You can specify a port number –port 3001
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"prepare": "husky install",
"json-server": "json-server __json_server_mock__/db.json --watch --port 3001"
},
Copy the code
- Start the command
yarn json-server
Copy the code
- Perform fetch list
- Perform the get subitem
- Perform add
- Implement changes
- To delete
What about non-restful interfaces
- Json-server also provides us with a set of interface extension methods
- Create a new middleware.js file in __json_server_mock__
- Take implementing a login interface as an example, using the Node HTTP module to create the interface
module.exports = (req, res, Next) = > {the if (the req. Method = = = "POST" & & the req. Path = = = "/ login") {if (the req. Body. The username = = = "George" & & the req. Body. The password = = = "123") { return res.status(200).json({ user: { token: "123", }, }); } else {return res.status(400). Json ({message: "wrong account or password ",}); } } next(); };Copy the code
- Modify the json-server command in package.json file
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"prepare": "husky install",
"json-server": "json-server __json_server_mock__/db.json --watch --port 3001 --middlewares ./__json_server_mock__/middleware.js"
},
Copy the code
- Run the json-server command again
- Verify the interface
extension
Restful API specification definition
Json – server’s official website