zoukankan      html  css  js  c++  java
  • nodejs实现路由转换的原理

    //路由:在服务器上,根据用户发送的path信息不同,返回不同的HTML数据

    //1 服务器:
    //2获取用户的请求数据:
    //3根据请求返回对应的内容

    const http = require('http')
    const url = require('url')
    const fs = require('fs')

    var server = http.createServer((req,res)=>{
    res.writeHead(200,{'Content-Type':'text/html'})
    // req.url 是有默认值的 (/一次请求 /favicon.ico 二次请求)

    if(req.url !== '/favicon.ico'){
    //console.log(req.url)
    const { pathname, query } = url.parse(req.url)
    if( pathname === '/'){
    // let mainTest = fs.readFileSync('./view/index.html','utf8')
    // //pathname是浏览器端发送的路径信息
    // res.write(mainTest)
    router_render('./view/index.html', res)
    }
    if( pathname === '/list'){
    // let mainTest = fs.readFileSync('./view/list.html','utf8')
    // res.write(mainTest)

    router_render('./view/list.html', res)
    }
    }
    //res.write('<h1>helloworld</h1>')
    //console.log( req.url)
    res.end()
    })

    function router_render(router_url, res){
    let mainTest = fs.readFileSync(router_url,'utf8')
    res.write(mainTest)
    }

    server.listen(8888,()=>{
    console.log('服务器启动成功')
    })

    server.on('error',(e)=>{
    console.log(e.message)
    })

    // if(req.url !== './favicon.ico'){
     
    // const {pathname, query} = url.parse(req.url)
    // if(pathname == '/') {
    // res.wirte('hello index')
    // }
    // if(pathname == '/list'){
    // res.write('hello list ')
    // }
    // }
  • 相关阅读:
    Linux下修改Tomcat默认端口
    java 中 byte[]、File、InputStream 互相转换
    安装mule-standalone说明
    python: 可变参数
    vim编码方式设置
    ASCII, Unicode 与 UTF-8
    Vim: 强大的g
    Vim模糊查找与替换
    Vim统计字符串出现次数
    APB简介
  • 原文地址:https://www.cnblogs.com/fengch/p/8619212.html
Copyright © 2011-2022 走看看