上次我们实现了如何通过不同的路由返回不同的内容。只返回一些文本内容未免也太鸡肋了,想要做功能强大又好看的页面,还是要用我们的 HTML 的。今天就讲一下怎么用 node.js 实现服务器通过路由返回不同的 HTML 文件。
这是上次内容的链接:Node.js 服务器根据不同的请求做出不同的响应
可以先看完前面关于 node.js 服务器的文章再接着看这篇,方便理解。
现在,开始实现我们今天要实现的功能了。
首先,肯定是先要导入我们的 http 模块。
// 加载 http 模块
var http = require("http");
然后,创建我们的 http 服务器,之前创建服务器的方法有点麻烦,需要经过下面的方法才能完全创建好一个服务器:
// 加载 http 模块
var http = require("http");
// 创建 http 服务对象
var server = http.createServer();
// 监听用户请求事件( request 事件)
// request 对象包含了用户请求报文中的所有内容 ,通过 request 对象可以获取所有用户提交过来后的数据
// response 对象用来向用户响应一些数据,当服务器要向客户端响应数据的时候必须使用 response 对象
server.on('request', function (request, response) {
...
})
// 启动服务
server.listen(8080, function () {
console.log('OK,访问:localhost:8080');
})
讲一个比较方便快捷的方法创建一个服务器:
// 加载 http 模块
var http = require("http");
// 创建服务
http.createServer(function (request, response) {
...
}).listen(8080, function () {
console.log("OK,访问:localhost:8080");
});
服务器创建好了,该设置我们浏览器的路由了,直接把上次的拷贝过来就行。
// 加载 http 模块
var http = require("http");
// 创建服务器
http.createServer(function (request, response) {
// 如果链接的路径是 / 或者 /index 时,返回的页面的 index 页面
if (