用Node.js原生代码实现静态服务器

时间:2023-01-24 05:04:24

---恢复内容开始---

后端中服务器类型有两种
1. web服务器【 静态服务器 】
- 举例: wamp里面www目录
- 目的是为了展示页面内容
- 前端: nginx
2. 应用级服务器[ api服务器 ]
- 后端接口
- tomcat
做什么?
- 使用Node.js原生代码实现静态服务器 【 必会 】
const http = require( 'http' )

const port = 3000

const hostname = 'localhost' // 127.0.0.1

http.createServer((request,response) => {

response.writeHead( 200, {
'Content-Type': 'text/html;charset=utf8' //如果输出内容含有中文,设置字符编码
}) response.write('hello Node.js') response.end() }).listen(port,hostname,() => {
// 参数: 端口 域名 监听回调
console.log(`The Server is running at: http://${ hostname }:${ port }`)
})

可以和爬虫结合使用,输出爬取的数据

可以和爬虫结合使用,输出爬取的数据
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 }`)
})

---恢复内容结束---