码迷,mamicode.com
首页 > Web开发 > 详细

nodejs中的路由

时间:2017-02-16 22:49:31      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:method   art   images   lang   login   world   query   创建   密码   

一、路由初步
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" >
</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‘), ‘‘)
}

nodejs中的路由

标签:method   art   images   lang   login   world   query   创建   密码   

原文地址:http://www.cnblogs.com/shenjp/p/6407025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!