1、express web服务器实现后端渲染
- 后端语言 + 后端渲染模板 生成前端的html结构,然后再发送到前台
const express = require( 'express' )
//得到app对象, 目的是为了绑定中间件
const app = express()
const PORT = 8000
const HOST = 'localhost'
const fs = require( 'fs' ) // 文件系统
app.get('/home',( request,response,next ) => {
fs.readFile( './static/html/index.html', 'utf8', ( error,docs ) => {
if( error ){
console.log( error )
}else{
response.send( docs )
}
})
})
// 监听服务器
app.listen( PORT,HOST,() => {
console.log( `服务器运行在: http://${ HOST }:${ PORT }` )
})
2、express api服务器如何暴露接口
-
首先打造接口,然后将模块导出,在服务器使用。
const express = require( 'express' ) const router = express.Router() //得到路由对象 模块创建 // 打造接口 router.get('/user', ( req,res,next ) => { res.json({ ret: true, name: 'zhangsan' }) }) module.exports = router // 模块的导出
const express = require( 'express' ) const app = express() //得到app对象 const PORT = 5000 const HOST = 'localhost' // 引入user路由模块 const userRouter = require( './route/user.js' ) app.use('',userRouter) //通过app对象使用路由模块 app.listen( PORT,HOST,() => { console.log( `api服务器` ) })
-
另外现在流行的接口是restful api,原理是根据请求方式的不同可以请求到不同的数据。
const express = require( 'express' ) const router = express.Router() //得到路由对象 模块创建 router .route('/user') .get(( req,res,next ) => { res.json({ ret: true, status: '查询成功' }) }) .post(( req,res,next ) => { res.json({ ret: true, status: '添加成功' }) }) .delete(( req,res,next ) => { res.json({ ret: true, status: '删除成功' }) }) .put(( req,res,next ) => { res.json({ ret: true, status: '修改成功' }) }) module.exports = router // 模块的导出
3、 express-generator生成器【脚手架】
概念:在Node.js中我们可以使用一个快速生成工具,帮助我们快速构建一个后端项目 ,这个工具叫做 express-generator 生成器 【 脚手架 】。
生成有两种方式:
-
全局安装
$ cnpm i express-generator -g express -e 项目名称
-
不使用全局安装,使用npx生成,但是要求npx对应的npm版本在 5.2 以上,npm5.2版本以上自动携带npx。
$ npx express -e 项目名称 -e表示使用ejs (-e 是可以被替换的)
- 拓展ejs,ejs的语法。
-
目录结构分析
bin www 创建服务器,并监听服务器 public 静态资源目录 img css routes 路由文件 view 模板文件 ejs/pug app.js 整个项目的入口文件 中间件绑定的 中间件类型 【 3种 】 应用级中间件( 只是一个单一功能, 如:绑定静态资源目录) 路由中间件 ( 暴露一个路由 ) package.json 记录项目依赖包配置信息和项目的命令脚本\