使用Node.js原生代码实现静态服务器
后端中服务器类型
- web服务器【静态服务器】
- 举例:wamp里的www目录
- 目的是为了展示页面内容
- 前端:nginx
- 应用级服务器【api服务器】
- 后端接口
- tomcat
使用Node.js原生代码实现静态服务器的步骤
- 传入模块,端口和域名
例
const http = require( 'http' );
const port = 3000 ;
const hostname = 'localhost' ;// 127.0.0.1
2.设置http的方法,监听
http.createServer((request,response) => {
response.write('hello Node.js');
response.end();
}).listen(port,hostname,() => {
// 参数: 端口 域名 监听回调
console.log(`The Server is running at: http://${ hostname }:${ port }`)//控制输出,服务器运行在哪里
});
如果输出内容含有中文,设置以下代码在监听函数中
response.writeHead( 200, {
'Content-Type': 'text/html;charset=utf8'
});
可以和爬虫结合使用,输出爬取的数据
const http = require( 'http' )
const port = 3000
const hostname = 'localhost' // 127.0.0.1
const cheerio = require( 'cheerio' )
const options = {
hostname: 'jx.1000phone.net',
port: 80,
path: '/teacher.php/Class/classDetail/param/rqiWlsefmajGmqJhXXWhl3ZiZGZp',
method: 'GET',
headers: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control':' no-cache',
Cookie: 'PHPSESSID=ST-22290-Uo8KnobsTgDO-TrQvhjA4TfoJI4-izm5ejd5j1npj2pjc7i3v4z',
Host: 'jx.1000phone.net',
Pragma: 'no-cache',
'Proxy-Connection': 'keep-alive',
Referer: 'http://jx.1000phone.net/teacher.php/Class/index',
'Upgrade-Insecure-Requests': 1,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 0
}
};
http.createServer((request,response) => {
response.writeHead( 200, {
'Content-Type': 'text/html;charset=utf8'
})
const req = http.get( options, (res) => {
const { statusCode } = res; // 获取状态码 1xx - 5xx
const contentType = res.headers['content-type']; // 文件类型 text/json/html/xml
res.setEncoding('utf8'); // 字符编码
// 核心 -- start
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); // 数据拼接
res.on('end', () => { // 数据获取结束
try {
const $ = cheerio.load( rawData )
$('td.student a').each( function ( item ) {
response.write( `<h3> ${ $( this ).text() } </h3>` )
})
response.end()
} catch (e) {
console.error(e.message);
}
});
// 核心 -- end
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
req.end()
}).listen(port,hostname,() => {
// 参数: 端口 域名 监听回调
console.log(`The Server is running at: http://${ hostname }:${ port }`)
})