持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第20天,点击查看活动详情
文章目录
前言
上篇文章我们介绍了nodejs的web服务器怎么响应json,以及json的生成和传输,详见博文:Node.js后端开发 - 基础篇 #10 web 服务器 part 2 响应 JSON,这篇文章我们将介绍web服务器怎么响应HTML页面文件!
响应 HTML 页面
好了步入正题,我们开始编码,把上篇文章的代码改改就可以了,如下:
var http = require('http');
var onRequest = function (request, response) {
console.log('Request received');
// response.writeHead(200, { 'Content-Type': 'text/plain' });//响应纯文本
// response.writeHead(200, { 'Content-Type': 'application/json' });//响应json
response.writeHead(200, { 'Content-Type': 'text/html' });//响应html文件
//定义字符串拼接的 html文件
var htmlFile = '<!DOCTYPE html>' +
'<html lang="en">' +
'<head>' +
'<meta charset="UTF-8">' +
'<meta name="viewport" content="width=device-width, initial-scale=1.0">' +
'<meta http-equiv="X-UA-Compatible" content="ie=edge">' +
'<title>这是html页面</title>' +
'</head>' +
'<body>' +
'hello wolrd'+
'</body>' +
'</html>'
//把HTML数据作为响应内容输出出来
response.end(htmlFile);
}
var server = http.createServer(onRequest);
server.listen(3000, '127.0.0.1');
console.log('server started on localhost port 3000');
我们先在终端启动server,如下:
MacBook-Pro:hello-nodejs luminal$ node app
server started on localhost port 3000
然后在谷歌 浏览器输入地址:http://localhost:3000/,效果如下:
编辑
我们课可以看到代码里面,title标签中:这是html页面,body标签中:hello world,刚好与浏览器显示对应的!
我们也可以查看浏览器中Response的响应内容,看看返回的数据,是不是和代码里面的内容一样的,如下:
编辑
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>这是html页面</title></head><body>hello wolrd</body></html>
响应 HTML 页面(HTML代码封装为文件读取)
上面的写法有些粗暴,而且难看不方便阅读,我们应该写一个html的文件,然后读取输出出来。这时候我们可以用到上几篇文章所讲到的知识来操作,就是用流和管道来操作一个文件,把文件的内容读取出来,我们来看看修改后app.js的代码
var http = require('http');
var fs = require('fs');
var onRequest = function (request, response) {
console.log('Request received');
response.writeHead(200, { 'Content-Type': 'text/html' });//响应html文件
var myReadStream = fs.createReadStream(__dirname + '/index.html', 'utf-8');
//把HTML数据作为响应内容输出出来
myReadStream.pipe(response);
}
var server = http.createServer(onRequest);
server.listen(3000, '127.0.0.1');
console.log('server started on localhost port 3000');
然后我们准备一个html文件:index.html,它的内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>这是一个html页面</title>
</head>
<body>
hello wolrd hello wolrd
</body>
</html>
同样像上面说的一样,我们启动sever,输入地址,同样可以看到html页面效果,这里就不贴代码演示了!
然后我们可以把代码,响应的头文件改一下,看一下效果
response.writeHead(200, { 'Content-Type': 'text/html' });//响应html文件
改成
response.writeHead(200, { 'Content-Type': 'text/plain' });//响应纯文本
然后我们看看浏览器输出的效果,如下:
编辑
它输出的就是纯文本的html代码,并没有像上面那样通过浏览器的解释和编译输出来的效果!