使用Node.js原生代碼實現靜態服務器

後端中服務器類型

  1. web服務器【靜態服務器】
    • 舉例:wamp裏的www目錄
    • 目的是爲了展現頁面內容
    • 前端:nginx
  2. 應用級服務器【api服務器】
    • 後端接口
    • tomcat

使用Node.js原生代碼實現靜態服務器的步驟

  1. 傳入模塊,端口和域名
const http = require( 'http' ); const port = 3000 ; const hostname = 'localhost' ;// 127.0.0.1 

2.設置http的方法,監聽php

http.createServer((request,response) => { response.write('hello Node.js'); response.end(); }).listen(port,hostname,() => { // 參數: 端口 域名 監聽回調 console.log(`The Server is running at: http://${ hostname }:${ port }`)//控制輸出,服務器運行在哪裏 }); 

若是輸出內容含有中文,設置如下代碼在監聽函數中html

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 }`) })
相關文章
相關標籤/搜索