zoukankan      html  css  js  c++  java
  • nodejs中的路由

    一、路由初步
    url.parse(string).query
    |
    url.parse(string).pathname |
    | |
    | |
    ------ -------------------
    http://localhost:8888/start?foo=bar&hello=world
    --- -----
    | |
    | |
    querystring.parse(string)["foo"] |
    |
    querystring.parse(string)["hello"]


    创建一个router_1.js
    var http = require('http')
    var url = require('url')

    http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
    if(req.url !== '/favicon.ico') {
    var pathName = url.parse(req.url).pathname
    console.log(pathName)
    }
    res.end()
    }).listen(8000)

    console.log('Server running at http://localhost:8000')


    安装supervisor模块,可以不用每次启动js,使用命令supervisor route_1.js


    创建一个modules/routers.js

    module.exports = {
    home: function(req, res) {
    res.write('首页')
    },
    login: function(req, res) {
    res.write('登录页面')
    },
    registor: function (req, res) {
    res.write('注册页面')
    }
    }

    修改router_1.js
    var router = require('./modules/router')

    var pathName = url.parse(req.url).pathname.replace(///, '')
    console.log(pathName)
    try {
    router[pathName](req, res)
    } catch(err) {
    router['home'](req, res)
    }
    二、读取图片文件
    将router_1.js另存为router_2.js
    更改头部信息如下
    res.writeHead(200,{"Content-Type":"image/jpeg"});
    在modules/router.js中添加读取文件路由
    img:function(req,res){
    file.readImg('./images/pet.jpg', res)
    }
    创建modules/file.js
    var fs = require('fs')
    readImg: function (file, res) {
    fs.readFile(file, 'binary', function (err, data) {
    if (err) throw err
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.write(data, 'binary')
    res.end()
    })
    }
    此时可以删除router_2.js中的res.end()
    在router.js中导入file.js
    var file = require('./file')

    此时发现如果在输出图片时没法正确显示
    res.write('test');
    res.write(data, 'binary')
    三、路由改造
    在file.js删除
    res.write('test');
    创建文件views/home.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <body>
    首页
    <!-- ./img为一个图片请求 -->
    <img src="./img" alt="">
    </body>
    </html>
    在file.js中创建一个模块readFile方法
    readFile: function (file, res, req) {
    fs.readFile(file, 'utf-8', function (err, data) {
    if (err) throw err
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
    res.write(data)
    res.end()
    })
    },
    更改touter2_.js中的代码,保证是一个干净的路由请求
    if(req.url !== '/favicon.ico') {
    var pathName = url.parse(req.url).pathname.replace(///, '')
    try {
    router[pathName](req, res)
    } catch(err) {
    router['home'](req, res)
    }
    }
    在router.js中的home路由中设置
    home: function(req, res) {
    file.readFile('./views/home.html', res, req)
    },
    四、参数接收

    创建文件views/login.html
    <form action="./login" method="get" >
    <label for="email">
    E-mail: <input type="text" name="email" value="" />
    </label>
    <label for="password">
    密码:<input type="password" name="password" value="" />
    </label>
    <label for="submit">
    <input type="submit" value="提交" />
    </label>
    </form>
    更改路由router.js中的login方法
    login:function(req,res){
    var urlObject = url.parse(req.url,true).query;
    console.log(urlObject.email)
    console.log(urlObject.password)
    file.readFile("./views/login.html",res,req);
    }

    post请求
    修改files.js
    引入querystring;
    var queryString = require('querystring')
    更改login方法
    login: function(req, res) {
    var post = ''
    req.on('data', function(chunk){
    post += chunk
    })
    req.on('end', function() {
    var urlObject = queryString.parse(post);
    console.log(urlObject.email)
    console.log(urlObject.password)
    file.readFile("./views/login.html",res,req);
    })
    },
    更改views/login.html中请求的方法
    action="./login" method="POST"

    如果需要将提交的数据显示到页面
    在file.js中添加一个方法
    postReadFile: function (file, res, req, post) {
    var urlObject = queryString.parse(post)
    var array = ['email', 'password']
    var reg;

    fs.readFile(file, 'utf-8', function(err, data){
    if(err) throw err
    res.writeHead(200, {'Content_Type': 'text/html; charset=utf-8'})

    for(var i = 0; i < array.length; i++) {
    reg = new RegExp('{' + array[i] + '}', 'gi')
    data = data.replace(reg, urlObject[array[i]])
    }
    res.write(data)
    res.end()
    })
    },
    更改router.js中的login方法
    req.on('end', function() {
    file.postReadFile('./views/login.html', res, req, post)
    })
    在login.html中添加显示信息
    <div >
    Email:{email}, 密码:{password}
    </div>
    如果第一次的时候我们发现显示不友好
    可以设置一个样式
    .hide{
    display:none
    }
    在div中添加class="{infoClass}"
    在form中设置class="{formClass}"
    在file.js中postReadFile中添加处理email和password代码,放在for循环之后
    if (urlObject.email && urlObject.password) {
    data = data.replace(new RegExp('{infoClass}', 'gi'), '')
    data = data.replace(new RegExp('{formClass}', 'gi'), 'hide')
    } else {
    data = data.replace(new RegExp('{infoClass}', 'gi'), 'hide')
    data = data.replace(new RegExp('{formClass}', 'gi'), '')
    }

  • 相关阅读:
    推荐有关微信开发的十个开源项目
    curl 常见错误码
    mysql修改root密码
    BAT批处理之文件与文件夹操作代码(附xcopy命令详解)
    UE4 Pak包加载
    libcurl 文件上传
    win7右键在目录当前打开命令cmd窗口
    SQLiteDeveloper破解
    Excel替换应用
    解决局域网2级路由互相连接共享的问题
  • 原文地址:https://www.cnblogs.com/shenjp/p/6407025.html
Copyright © 2011-2022 走看看