NodeJS路由是非常关键的。我们要为路由提供请求的 URL 和其他需要的 GET 及 POST 参数,随后路由需要根据这些数据来执行相应的代码。
因此,我们需要查看 HTTP 请求,从中提取出请求的 URL 以及 GET/POST 参数。这一功能应当属于路由还是服务器(甚至作为一个模块自身的功能)确实值得探讨,但这里暂定其为我们的HTTP服务器的功能。
我们需要的所有数据都会包含在 request 对象中,该对象作为 onRequest() 回调函数的第一个参数传递。但是为了解析这些数据,我们需要额外的 Node.JS 模块,它们分别是 url 和 querystring 模块。
说白了就是根据URL和请求方法来获取参数,使用request方法来获取GET或者POST的参数。根据参数执行相应的代码。
获取路由路径
http.js
const http = require("http");
const url = require("url");
function start() {
function onRequest(req, res) {
const pathname = url.parse(request.url).pathname;
console.log("request for" + pathname + " received.");
res.writeHead(200, { "Content-Type": "text/plain" });
res.write("hello world");
res.end();
}
http.createServer(onRequest).listen(8888);
console.log("服务器启动成功");
}
exports.start = start;
app.js
const server = require("./http");
server.start();
此时启动app 控制台会输出 服务器启动成功
浏览器访问 http://localhost:8888/ 页面会输出hello world 然后控制台打印 Request for / received 这个是根路由。
浏览器访问 http://localhost:8888/a/b 页面输出不变 但是控制台打印就不一样了 Request for /a/b received 这样一个输出。因为 代码中 pathname 就代表了我们在端口号之后的 URL 路径,也就是路由。页面输出没有变化是因为根本没有对路由有响应的处理。
这里 可以理解为 /controller/action。
路由和服务器结合
router.js
function route(pathname) {
console.log("路由是" + pathname);
}
exports.route = route;
这段代码什么也没干,是的下面就看看如何把路由和服务器结合起来。
http.js
const http = require("http");
const url = require("url");
function start(route) {
function onRequest(req, res) {
const pathname = url.parse(request.url).pathname;
route(pathname,res);
res.writeHead(200, { "Content-Type": "text/plain" });
res.write("hello world");
res.end();
}
http.createServer(onRequest).listen(8888);
console.log("服务器启动成功");
}
exports.start = start;
app.js
const server = require("./http");
const route = require("./router");
server.start(route.route);
把router模块通过参数传递给http模块。然后http去执行router模块。router模块就会接受到路由地址然后会打印出路由。
这个时候访问浏览器: http://localhost:8888/a/c 控制台就会打印 路由是 /a/c。
目前 router 模块其实并没有什么用。如何让它有用?
http.js 把 response 传入router中
const http = require("http");
const url = require("url");
function start(route) {
function onRequest(request, response) {
const pathname = url.parse(request.url).pathname;
route(pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("服务器启动成功");
}
exports.start = start;
router.js 接受到之后做响应的操作
function route(pathname, response) {
if (pathname == "/") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.write("Hello World");
response.end();
} else if (pathname == "/index/home") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("index/home");
} else {
response.end("404");
}
}
exports.route = route;
此时启动app.js
浏览器访问http://localhost:8888/ 页面输出 hello world
浏览器访问http://localhost:8888/index/home 页面输出 index/home
浏览器访问http://localhost:8888/bbb 页面输出 404
这样拿到路由就能根据路由返回响应的内容了。
现在还没有通过GET和POST去拿参数。
GET和POST请求
GET
const http = require("http");
const url = require("url");
const util = require("util");
http
.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(util.inspect(url.parse(req.url, true)));
})
.listen(3000);
浏览器访问http://localhost:3000/user?name=yideng&age=30 页面输出:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: ‘?name=yideng&age=30’,
query: [Object: null prototype] { name: ‘yideng’, age: ‘30’ },
pathname: ‘/user’,
path: ‘/user?name=yideng&age=30’,
href: ‘/user?name=yideng&age=30’
}
获取 URL 的参数
const http = require("http");
const url = require("url");
const util = require("util");
http
.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/plain;charset=utf-8" });
// 解析 url 参数
const params = url.parse(req.url, true).query;
res.write("网站名:" + params.name);
res.write("\n");
res.write("网站 URL:" + params.url);
res.end();
})
.listen(3000);
浏览器访问http://localhost:3000/user?name=百度&url=www.baidu.com
网站名:百度
网站 URL:www.baidu.com
POST
const http = require("http");
const querystring = require("querystring");
let postHTML =
'<html><head><meta charset="utf-8"><title>Node.js 实例</title></head>' +
"<body>" +
'<form method="post">' +
'网站名: <input name="name"><br>' +
'网站 URL: <input name="url"><br>' +
'<input type="submit">' +
"</form>" +
"</body></html>";
http
.createServer((req, res) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
// 解析参数
body = querystring.parse(body);
// 设置响应头部信息及编码
res.writeHead(200, { "Content-Type": "text/html; charset=utf8" });
if (body.name && body.url) {
// 输出提交的数据
res.write("网站名:" + body.name);
res.write("<br>");
res.write("网站 URL:" + body.url);
} else {
// 输出表单
res.write(postHTML);
}
res.end();
});
})
.listen(3000);
首先给页面返回一个表单,然后这个表单提交过来的内容回显到页面。