路由的基本使用

第一步:获取url跟目录下的字符

var http = require('http');
var url = require('url') http.createServer(function (request,response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url !== "/favicon.ico"){ //拿到浏览器访问的url路劲,并且替换掉前面的/
var pathname = url.parse(request.url).pathname.replace(/\//, '')
console.log(pathname) response.end("")
}
}).listen(9000)

浏览器访问http://localhost:9000/login

后台拿到访问路劲login

第二步:路由功能的实现

首先创建一个路由模块文件router.js,下面代码分别由login和register

这种方式其实就是根据pathname来调用router中的login或者register方法

module.exports = {
login (req,res) {
res.write("我是login方法")
},
register (req,res) {
res.write('我是register方法')
}
}
var http = require('http'); //http是node中自带的一个模块,引入即可使用
var url = require('url');
var router = require('./router'); http.createServer(function (request,response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url !== "/favicon.ico"){ var pathname = url.parse(request.url).pathname.replace(/\//, ''); try {
router[pathname](request,response);
}catch(err) {
console.log(err)
}
response.end("")
}
}).listen(9000)

如果在后面输入不存在的,则打印出错误信息

路由结合读取文件

首先创建两个html文件,login.html和register.html

创建主程序app.js

var http = require('http');
var url = require('url')
var router = require('./router') http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url !== "/favicon.ico"){
var pathName = url.parse(request.url).pathname.replace(/\//, '')
router[pathName](request,response)
response.end();
}
}).listen(9000)

创建路由模块router.js

这是路由模块的文件,这里会使用到闭包函数,还会用到读取文件的模块,这里先调用读取文件模块中的异步读取,传入闭包函数

最新文章

  1. Codeforces Beta Round #7
  2. Dynamic CRM 2013学习笔记(三)快速创建实体 EntityCreater
  3. uva 12655 Trucks [LCA](树链剖分+MST)
  4. ARM状态和THUMB状态
  5. Hint
  6. C语言的几种取整方法
  7. ApiCloud重新定义移动应用开发
  8. BOM-字节序标记
  9. 【转】perl如何避免脚本在windows中闪一下就关闭
  10. Linux下编译安装redis,详细教程
  11. Spring Boot Web项目之参数绑定
  12. NSNumber与NSInteger的区别 -bei
  13. 库函数 Math
  14. C++中的函数模板
  15. Storm官方文档翻译之设置开发环境
  16. hdu_1045Fire Net(二分图匹配)
  17. Mybatis中的CDATA标签
  18. Lake Counting
  19. ORA-27157 ORA-27300 ORA-27301
  20. PHP中的 抽象类(abstract class)和 接口(interface)

热门文章

  1. BCryptPasswordEncoder 判断密码是否相同
  2. windows下PyTorch安装之路记录
  3. 「vue基础」一篇浅显易懂的 Vue 路由使用指南( Vue Router 下)
  4. 安全漏洞系列(一)---XSS漏洞解决方案(C# MVC)
  5. 在IIS下发布.Net Core MVC项目
  6. Git远程协作和分支
  7. Python学习笔记之replace()
  8. http 307重定向
  9. JavaScript之二十三种设计模式
  10. 移动端调试神器vconsole,手机端网页的调试工具Eruda