node.js 路由
路由就是根据请求不同的路径,做不同的事情。
1.先看看常规的:
server.js里:
var http = require('http'); var url = require('url'); function start() { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("request for" + pathname + "received"); response.writeHeader(200, {"Content-Type":"text/plain"}); response.write("Hello SHISHI"); response.end(); } http.createServer(onRequest).listen(8888); console.log("server started"); } exports.start = start;
start.js里:
var server = require('./server'); server.start();
2. 再加上路由
server.js里:
start.js里:
route.js里:
启动:
访问:
再看访问的控制台
3.再看看怎么获取url上的参数
var http = require('http'); var url = require('url'); var querystring = require('querystring'); function start() { function onRequest(request, response) { //获取url对象 var myurl = url.parse(request.url); console.log(myurl); console.log('..........'); //获取request对象参数 var paramObj = querystring.parse(myurl.query); console.log(paramObj); response.writeHeader(200, {"Content-Type":"text/plain"}); response.write("Hello SHISHI"); response.end(); } http.createServer(onRequest).listen(8888); console.log("server started"); } start();
启动看看:
访问:http://localhost:8888/?a=111&b=222
1是url对象
2是参数字符串解析成的对象