如何使用 JSON 服务器为你的项目创建伪 REST API
你可能经常会搭建一个演示网站,或者一个练习项目,需要一些数据。比如,假设你正在搭建一个时尚网站的演示版,需要一些数据来展示待售商品。你会怎么做?
- 您可以使用现有的 API,但如果没有合适的 API 怎么办?
- 您也可以对数据进行硬编码,但之后如果决定连接 API,则需要更改代码。您可能还需要练习/演示如何调用 API 端点。
使用JSON 服务器,您可以创建一个在本地运行的虚假 API(非常适合开发或只是需要它来展示演示!)并且像任何其他 API 一样工作!
首先,安装 JSON 服务器
npm install -g json-server
要充当“数据库”,您需要创建一个名为 db.json 的文件(我通常将其放在项目根目录中)。在这里,您将创建一个 JSON 对象,并指定一个键作为 API 端点。假设我正在创建一个销售包袋的网站。我只想在这里添加 3 个商品:
{
"bags": [
{
"id": 1,
"title": "Stylish Bag",
"color": "orange",
"imgurl": "https://images.unsplash.com/photo-1584917865442-de89df76afd3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1035&q=80",
"stock": 10
},
{
"id": 2,
"title": "Cool Bag",
"color": "black",
"imgurl": "https://images.unsplash.com/photo-1548036328-c9fa89d128fa?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2069&q=80",
"stock": 5
},
{
"id": 3,
"title": "Interesting Bag",
"color": "blue",
"imgurl": "https://images.unsplash.com/photo-1594223274512-ad4803739b7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1057&q=80",
"stock": 17
}
]
}
创建数据后,在终端中使用以下命令:
json-server --watch db.json
太棒了!现在你可以通过localhost:3000/bags访问你的 API 了!
现在,它的行为与其他 REST API 类似。例如,如果您想在 React 应用中使用它,您可以调用“bags”端点并获取数据。以下是其中一个例子:
useEffect(() => {
axios
.get("http://localhost:3000/bags")
.then((res) => {
setData(res.data);
})
.catch((error) => {
console.log(error);
});
}, []);
尖端
更改端口
如果您不想让 json-server 在端口 3000 上运行(也许您的前端在那里运行),您可以像这样更改端口:
json-server --watch -p 4000 db.json
多个端点
您可以拥有多个端点!只需向您的对象添加另一个密钥即可。这里我添加了“wallets”:
{
"bags": [
{
"id": 1,
"title": "Stylish Bag",
"color": "orange",
"imgurl": "https://images.unsplash.com/photo-1584917865442-de89df76afd3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1035&q=80",
"stock": 10
},
{
"id": 2,
"title": "Cool Bag",
"color": "black",
"imgurl": "https://images.unsplash.com/photo-1548036328-c9fa89d128fa?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2069&q=80",
"stock": 5
},
{
"id": 3,
"title": "Interesting Bag",
"color": "blue",
"imgurl": "https://images.unsplash.com/photo-1594223274512-ad4803739b7c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1057&q=80",
"stock": 17
}
],
"wallets": [
{
"id": 1,
"title": "Leather Wallet",
"color": "black",
"imgurl": "https://images.unsplash.com/photo-1612023395494-1c4050b68647?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1480&q=80",
"stock": 10
}
]
}
现在如果你运行
json-server --watch db.json
再次,您可以访问包或钱包端点:
请务必检查json-server 文档以了解您还可以做什么,我希望这对您的项目有所帮助!
文章来源:https://dev.to/tiaeastwood/how-to-create-a-fake-rest-api-for-your-project-with-json-server-214e