mvc
m:model 数据层
v:view 视图层
c: controller 控制层
编写控制层&router
app.js
const express=require('express')
const cors=require('cors')
const apiRouter=require('./router/apiRouter')//引入router模块
const app=express()
app.use(cors()) //允许跨域
app.use(express.urlencoded({extended:false})) //解析xxx-form-urlencoded 相当于bodyParse(获取输入的数据)
app.use(express.json()) //接收json数据类型
//范围
app.use('/api',apiRouter)
app.listen(8181,()=>{
console.log('服务器启动成功');
})
router.js
const express=require('express')
const apiController = require('../controller/apiController')
//创建路由器对象
const apiRouter=express.Router()
//路由器规则
apiRouter.get('/add',apiController.add)
apiRouter.get('/delete',apiController.delete)
apiRouter.get('/update',apiController.update)
apiRouter.get('/query',apiController.query)
module.exports=apiRouter
controller.js
class aipController{
async add(req,resp,next){
resp.send('add')
}
async delete(req,resp,next){
resp.send('delete')
}
async update(req,resp,next){
resp.send('update')
}
async query(req,resp,next){
resp.send('query')
}
}
module.exports=new aipController()
编写视图层
app.js
const express=require('express')
const artTmplate=require('express-art-template')
const app=express()
app.engine('art',artTmplate)
app.set('views','./views')
app.set('view engine','art')
//2.配置静态资源
app.use(express.static('./public'))
app.get('/',(req,resp)=>{
})
var arr=[
{id:1,name:'刘德华'},
{id:2,name:'蔡徐坤'}
]
app.get('/login',(req,resp)=>{
var oUser={id:1,name:"刘德华",pwd:123}
resp.render('login',{data:oUser,
val:'我是string',arr,flag:true})
})
app.listen(8282,()=>{
console.log('服务器启动成功');
})
view.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./css/login.css">
<script src="./js/jquery.js"></script>
<script>
$(function(){
setTimeout(() => {
$('body').css('backgroundColor','green')
}, 3000);
})
</script>
</head>
<body>
<form>
<input type="text" value="{{data.name}}" name="name" placeholder="用户名"><br>
<input type="text" value="{{data.pwd}}" name="pwd" placeholder="密码"><br>
<button>登录</button>
</form>
<p>{{val}}</p>
<p>{{arr}}</p>
<p>arr==={{arr[0]}}</p>
<p>
{{each arr}}
<p>我是下标 {{$index}}</p>
<p>我是内容{{$value["id"]}}--{{$value.name}}</p>
{{/each}}
</p>
<p>
{{if flag}}
<div>我显示了</div>
{{/if}}
</p>
<p>{{@val}}</p>
<h1>origin语法</h1>
<%-val %>
</body>
</html>
使用express的快速生成器
https://www.expressjs.com.cn/en/starter/generator.html
$ npm install -g express-generator
$ express
express xxx项目名 --no-view