后端路由

后端路由,其实就是一个web服务器。通过用户请求的url导航到具体的html页面;每跳转到不同的URL,都是重新访问服务端,然后服务端返回页面,页面也可以是服务端获取数据,然后和模板组合,返回HTML,也可以是直接返回模板HTML,然后由前端js再去请求数据,使用前端模板和数据进行组合,生成想要的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 }` )
  })

posted @ 2019-07-17 16:32  everjin  阅读(824)  评论(0编辑  收藏  举报