- http模块
1.http-server.js 创建静态服务器
/*
-
后端服务器有两种类型
- web服务器 【 静态服务器 】
- api服务器 【 暴露接口 】
-
请求头部报文 四部分组成:
- general 请求基本信息
- response Headers 响应头
- request Headers 请求头
- 携带参数
- query string paramters get请求
- form data post 请求
const http = require( 'http' )
const host = 'localhost' //域名
const port = 8000 //端口
http.createServer(( request,response ) => {
// response.writeHead( 状态码,请求头 )
response.writeHead( 200, {
'Content-type': 'text/html;charset=utf8'
})
response.write('<h3> 这里使用Node创建的一个静态服务器 </h3>') // 往前端发送信息
response.end() // 告诉前端信息已经结束了
}).listen( port,host,() => {//链式调用
console.log( `The server is running at: http://${ host }:${ port }` )
//提示语:这个服务器运行在哪个地址下
})
2.http-spider.js 爬取一段特定数据(下面爬取了一些姓名)
/*
http模块
爬虫
* 去某一个网站爬取一段数据 -> 数据清洗(一段特定数据) -> 后端服务器 -> 发送前端 -> 渲染数据
* 不是所有网站都可以爬取
* 反爬虫
* 爬虫: 后端渲染的网站 (跟前端页面没关系)
const http = require( 'http' )
// 引入第三方类库 cheerio:nodejs的抓取页面模块 npm install cheerio
const cheerio = require( 'cheerio' );
const options = {//主要含'-'的对象名加上引号,内容也都加上引号
hostname: 'aaaaaaaaa.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-159231-9hv0Ja04QabYv-n5OYwWsQFVfjw-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/75.0.3770.100 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 0
}
}
http.get( options, (res) => {//去nodejs网站搜索 http.get()的用法
const { statusCode } = res; // 获取请求状态码 200 301 302 303 304 404 500
const contentType = res.headers['content-type']; // 获取请求类型数据类型
// json数据的content-type 'content-type': 'application/json'
res.setEncoding('utf8'); // 字符编码
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); // 通过data事件拼接数据流
res.on('end', () => { // 获取数据结束了
try { // 高级编程语法 捕获错误信息
// console.log( rawData ) //rawData是带有HTML结构的一个字符串
const $ = cheerio.load( rawData )
$('td.student a').each(function (index,item) {
//a标签当前肯定是个集合,用each遍历来输出a标签中的文字
console.log( $( this ).text() + '---' + index )
})
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
http-spider-server.js (将上面抓取数据并数据清洗后的结果给前台)
const http = require( 'http' )
const host = 'localhost'
const port = 8000
http.createServer(( request,response ) => {
// response.writeHead( 状态码,请求头 )
response.writeHead( 200, {
'Content-type': 'text/html;charset=utf8'
})
const http = require( 'http' )
// 引入第三方类库
const cheerio = require( 'cheerio' )
const options = {
hostname: 'aaaaaaaaa.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-159231-9hv0Ja04QabYv-n5OYwWsQFVfjw-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/75.0.3770.100 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 0
}
}
http.get( options, (res) => {
const { statusCode } = res; // 获取请求状态码 200 301 302 303 304 404 500
const contentType = res.headers['content-type']; // 获取请求类型数据类型
// json数据的content-type 'content-type': 'application/json'
res.setEncoding('utf8'); // 字符编码
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); // 通过data事件拼接数据流
res.on('end', () => { // 获取数据结束了
try { // 高级编程语法 捕获错误信息
// console.log( rawData )
const $ = cheerio.load( rawData )
$('td.student a').each(function (index,item) {
response.write(`<h3> ${ $( this ).text() } </h3>`) // 往前端发送信息
})
response.end() // 告诉前端信息已经结束了
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});}).listen( port,host,() => {
console.log( `The server is running at: http://${ host }:${ port }` )
})
events模块
Node.js中 事件的发布 + 事件的订阅 表示一个任务的执行
const Events = require('events')
const fs = require( 'fs' )
const http = require( 'http' )
const host = 'localhost'
const port = 3000
class myEvent extends Events{} //类的继承
const myevent = new myEvent() // 实例化类得到一个实例 //把原型身上的东西继承下来
// console.log( myevent )
//事件的发布
// myevent.on(事件名称,事件的回调函数)
myevent.on('aa',function () {
// 书写任务
// 任务: 将yyb.txt中的内容发送前台
http.createServer( ( req,res ) => {
res.writeHead( 200,{
'Content-Type': 'text/html;charset=utf8'
})
// 1
fs.readFile('./yyb.txt','utf8',( error,docs ) => {
// error作为第一个参数的回调函数,我们叫做错误优先的回调函数
res.write(`<h3> ${ docs } </h3>`)
res.end()
})
//res.end() 放这会有错
//因为这一步比上面先执行,因为上面的是在回调函数里的即异步的 ,而res.end()放外面则在主线程,所以快于上面执行。
}).listen( port,host,() => {
console.log( `服务器运行在: http://${ host }:${ port }` )
})
})
// 事件的订阅
// myevent.emit(事件名称)
myevent.emit( 'aa' )
后端代理
反向代理的基本原理: transpond(转发)
我们的后端帮助我们请求数据 , 在将数据发送给我们自己前端
任务:
1. 后端请求数据
2. 将数据发送给前端 api服务器 express
const request = require( 'request' )
const express = require( 'express' )
const host = 'localhost'
const port = 3000
const app = express()
const url = 'https://m.lagou.com/listmore.json'
//创建接口
app.get('/position', ( req,res,next ) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // 设置请求头跨域
// 数据请求
request( url, ( error,response,body ) => {
res.json( JSON.parse( body ) )
})
})
app.listen( port,host, () => {
console.log( `The server is running at: http://${ host }:${ port }`)
})
前端页面调用上面创建的接口:
proxy(代理)
/*
后端
api服务器
Node.js中api服务器的创建,使用一个第三方库 express
后端解决跨域问题:
1. 设置请求头
2. 使用中间件
const express = require( 'express' )
const app = express() // 得到一个app对象
const port = 3000
const host = 'localhost'
// 创建接口
app.get( '/user', ( req,res,next ) => { // 回调函数我们称之为: 中间件 具有特定功能的一个函数
console.log( req.headers.origin )
res.setHeader('Access-Control-Allow-Origin', '*'); // 设置请求头跨域
res.json({
id:12,
name: 'susan',
class: '五班'
})
})
app.get( '/demo', ( req,res,next ) => { // 回调函数我们称之为: 中间件 具有特定功能的一个函数
res.setHeader('Access-Control-Allow-Origin', '*'); // 设置请求头跨域
res.json({
id: 10,
name: 'lisa',
class: '三班'
})
})
// 创建api服务器,并监听这个服务器
app.listen( port,host,() => {
console.log( `The server is running at : http://${ host }:${ port }` )
})