json-server
介绍
在前端开发中,数据一般通过后端接口获得。而我们在自己写一些项目练手的时候,需要一些数据,而又没有后端支持,可以通过json-server以零代码的方式获得一个完整的REST(get,post,put,delete增删改查) API。来启动一个本地json服务。
使用
1、全局安装:
npm install -g json-server
2、创建一个db.json文件,创建几条需要的数据
3、启动json-server
在项目目录下打开终端输入命名:json-server --watch db.json --port 8000
注:--port 端口号用来定义端口,可不写,默认3000.
结果如下:
打开这两个uri可以看到有数据:
接下来,就可以在我们的项目中使用了
3、在项目中使用:
const getData =async () => {
const res = await fetch('http://localhost:8000/products');
const product = await res.json();
console.log(product)
}
在浏览器中可以看到获取到了数据:
注:fetch是浏览器的API,如果在nodejs中运行,需要安装引入node-fetch。
查询操作:
如果要查询某一条数据呢?比如点击一个商品进入这个商品详情。 需要将要查询的数据作为参数传到下一个页面。
新增一个details页面
const container = document.querySelector('.container');
const getData = async () => {
const res = await fetch("http://localhost:8000/products");
const product = await res.json();
let template = ``;
product.forEach(p => {
template += `
<div>
<h2>${p.title}</h2>
<a href="./details.html?id=${p.id}">go ${p.title}</a>
</div>
`
})
container.innerHTML = template;
};
getData();
浏览器打开效果:
在details页面中:
const details = document.querySelector('.details');
// 获取上个页面传过来的参数
let id = new URLSearchParams(window.location.search).get('id');
const getDetail = async () => {
const res = await fetch('http://localhost:8000/products/' + id);
const product = await res.json()
const template = `
<h2>${product.title}</h2>
<p>${product.description}</p>
`
details.innerHTML = template;
}
getDetail()
看下效果:
成功获取到我们想要的那条数据。
增加操作:
增加一个表单页面,监听表单的submit事件。
const addProduct = async (e) => {
e.preventDefault();
const newProduct = {
title: e.target.title.value,
description: e.target.body.value,
price: e.target.price.value
}
await fetch('http://localhost:8000/products',{
method: 'POST',
body: JSON.stringify(newProduct),
headers: {'Content-Type': 'application/json'}
})
window.location.replace('/index.html')
}
window.addEventListener('submit',addProduct)
看下效果:
看下db.json文件:
新增成功!还自己添加了id
删除操作:
在details页面添加一个删除按钮,监听按钮的点击事件。
details.js中
const details = document.querySelector('.details');
const deleteBtn = document.querySelector('.deleteBtn');
// 获取上个页面传过来的参数
let id = new URLSearchParams(window.location.search).get('id');
const getDetail = async () => {
const res = await fetch('http://localhost:8000/products/' + id);
const product = await res.json()
const template = `
<h2>${product.title}</h2>
<p>${product.description}</p>
`
details.innerHTML = template;
}
getDetail()
deleteBtn.addEventListener('click', async (e) => {
const res = await fetch('http://localhost:8000/products/' + id, {
method: 'DELETE'
})
window.location.replace('/index.html')
})
将刚刚新增的那条删除,看下效果:
再看下db.json文件
删除成功!
搜索
列表页加个搜索框。
<form class="search">
<input type="text" placeholder="搜索" name="term">
</form>
js部分:
const container = document.querySelector('.container');
const searchForm = document.querySelector('.search');
const getData = async (term) => {
let uri = 'http://localhost:8000/products'
// term 搜索关键词
if(term) {
// 将搜索词拼接到uri
uri += `?q=${term}`
}
const res = await fetch(uri);
const product = await res.json();
let template = ``;
product.forEach(p => {
template += `
<div>
<h2>${p.title}</h2>
<a href="./details.html?id=${p.id}">go ${p.title}</a>
</div>
`
})
container.innerHTML = template;
};
getData();
// 搜索
searchForm.addEventListener('submit', async (e) => {
e.preventDefault();
getData(searchForm.term.value.trim())
})
看下效果:
没毛病!
结语
以上就是用json-server实现一个本地json服务器,可以模拟数据库的增删改查,对平时自己写demo很有用。
转载自:https://juejin.cn/post/7179494971953643557