Node.js-路由
# Node.js 路由
解析以下URL,我们需要 Node.JS 模块,它们分别是 url 和 querystring 模块
http://localhost:8888/start?foo=bar&hello=world
1
数据如下:
start:url.parse(string).pathname
foo=bar&hello=world:url.parse(string).query
bar:querystring.parse(queryString)["foo"]
world:querystring.parse(queryString)["hello"]
创建server.js 文件
onRequest() 函数加上一些逻辑,用来找出浏览器请求的 URL 路径
var http = require("http");
var url = require("url");
function start(route) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
创建 router.js 的文件
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;
1
2
3
4
5
2
3
4
5
相应扩展 index.js,使得路由函数可以被注入到服务器中
var server = require("./server");
var router = require("./router");
server.start(router.route);
1
2
3
4
2
3
4
上次更新: 2024/08/14, 04:14:33