Node后端路由基本原理
——后端框架express的路由的基本原理
-
后端路由其实就是一个web服务器
-
路由:
- 路:url路径
-
以前:多页面
index.html a标签 herf = “./detail.html”
a标签 herf = “./shopcar.html”
-
现在流行:单页面
index.html
我们这个时候,会将detail/shopcar做成模板 [ ejs pug(jade) 【 Node.js专用】 art-template[ 后端使用 ] ],替换index.html里面的内容
-
-
代码例子
const http = require( 'http' )
const host = 'localhost'
const fs = require( 'fs' )
const port = 5000
http
.createServer( ( req,res ) => {
res.writeHead( 200,{
'Content-type': 'text/html;charset=utf8'
})
switch ( req.url ) {
case '/home':
res.write('home')
res.end()
break;
case '/shopcar':
fs.readFile( './static/shopcar.html', 'utf8',( error,docs ) => {
res.write( docs )
res.end()
})
break;
case '/1.jpg':
fs.readFile( './static/1.jpg',( error,docs ) => {
// 图片是以二进制传输的
res.write( docs, 'binary')
res.end()
})
break;
case '/index.js':
fs.readFile( './static/js/index.js',( error,docs ) => {
// 图片是以二进制传输的
res.write( docs )
res.end()
})
break;
default:
break;
}
})
.listen( port,host,() => {
console.log( `服务器运行在:http://${ host }:${ port }` )
})
附:
后端服务器有两种类型
- web服务器 【静态服务器】
- api服务器 【暴露接口】