nodejs创建路由

2019-06-11  本文已影响0人  BULL_DEBUG

var http = require('http')
var url = require('url')

var router = require('./modules/router')

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.replace(/\//, '')
        console.log(pathName);
        try {
            router[pathName](req, res)
        } catch (err) {
            router['home'](req, res)
        }
       
    }
    res.end();
}).listen(8000);
console.log('Server running at http://localhost:8000')
module.exports = {
    home: function(req, res) {
        res.write('首页')
    },
    login: function(req, res) {
        res.write('登录页面')
    },
    registor: function (req, res) {
        res.write('注册页面')
    }
}

二,读图片页面

var fs = require('fs')

module.exports = {
    readFile: function (file, res, rep) {
        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();
        })
    },
    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()
       }) 
    }
}
var file = require('./file')
module.exports = {
    home: function(req, res) {
       file.readFile('./views/home.html', res, req)
    },
    login: function(req, res) {
        res.write('登录页面')
    },
    registor: function (req, res) {
        res.write('注册页面')
    },
    img: function (req, res) {
        file.readImg('./images/pet.jpg', res)
    },
}
var http = require('http')
var url = require('url')

var router = require('./modules/router')

http.createServer(function(req, res) {
    // res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})
    // res.writeHead(200, {'Content-Type': 'images/jpeg'})
    if (req.url !== '/favicon.ico') {
        var pathName = url.parse(req.url).pathname.replace(/\//, '')
        console.log(pathName);
        try {
            router[pathName](req, res)
        } catch (err) {
            router['home'](req, res)
        }
       
    }
    // res.end();
}).listen(8000);
console.log('Server running at http://localhost:8000')
上一篇 下一篇

猜你喜欢

热点阅读