首先目录结构如图所示:
个人风格问题吧,我一般喜欢写完后台的东西再写页面,我们先看server.js 这个文件里面的东西吧,这个文件主要是写模拟后台的东西
const express = require('express')
const fs = require('fs');
const students = require('./json')
const app = express();
// 静态资源服务器
app.use(express.static('./public',{
maxAge: 1000*60*60*24*2,
}))
app.use(function(req, res, next){
// fs.readFile('./public/index.html',(err, content)=>{
// res.set({
// 'Content-Type': 'text/html;charset=utf-8'
// });
// res.send(content)
// })
next()
})
app.get('/students', (req, res)=>{
res.send(students)
})
app.get('/cars',(request,response)=>{
const cars = {
data: [
{id:'001',name:'奔驰',price:199},
{id:'002',name:'马自达',price:109},
{id:'003',name:'捷达',price:120},
],
code: 200,
page: 1,
pageSize: 10,
total: 50
}
response.send(cars)
})
const PORT = 2021;
app.listen(PORT, ()=>{
console.log('服务器已启动:http://localhost:2021/');
})
注意点是:该引入的按照文档引入就行了,在中间件里面要调用 next()才能进入下一个中间件, 给前端返回数据的原理也比较简单,匹配上路径,例如:'/cars',就执行对应的回调,把自己定义的数据send()给前端就行了,当然我这里的数据是写死的,可以连接数据库,加上相对应的crud语句就可以实现,模拟接口的请求了;
说到模拟数据请求岂能少的了前端页面,下面先上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>哈哈 node</h1>
<img src="https://img1.baidu.com/it/u=1719063513,2559625643&fm=26&fmt=auto" alt="">
<button id="res">请求</button>
<script>
document.querySelector('#res').onclick = function(){
fetch('http://localhost:2021/cars')
.then(
res => res.json(),
err => console.log(err)
)
.then(res =>
console.log('res',res)
)
// .then(response => response.json())
// .then(data => console.log(data));
}
</script>
</body>
</html>
我这里使用fetch发送的异步请求哈,为什么不使用axios呢,就是纯粹的懒,因为axios需要安装;说一下这段前端页面代码吧;
页面上有一个按钮,主要是模拟点击发送请求用的,重点是fetch的使用,它的第一个then是拿不到数据,必须在里面返回一个xxx.json(),才能在第二个then里面拿到数据;
可以连续使用then方法的原因是,上一个then返回的也是一个promise,不用自己手动的在上一个then里面new Promise(),它自然而然的会返回一个promise
整个模拟请求就结束了,当然可以使用网上的mock去模拟请求数据也可以(比较推荐这个,能快速用到开发里面)