http
- 使用Node.js实现一个web服务器
2. Node.js中模块的api很多时候可以连缀(链式调用)
(1).createServer (创建一个web静态服务器 )
(2) listen (是用来监听当前服务器)
(3) 3. 名词解释
1. port 端口
2. hostname: 域名
3. request 请求, Node.js请求谁
4. response 回应]
5. data 数据
6. encoding; 编码方式 utf8 默认utf8
(4) write(data,encoding) 给前台发送一个内容
(5) end() 发送已经结束了
(6) 中文乱码问题:
方案一:
response.writeHead(200,{ 'Content-Type': 'text/html; charset=UTF-8' })
方案二:
response.write('<head> <meta charset="UTF-8"> </head>')
格式:http.createServer(callback).listen(prot,hostname,callback)
url
1. 用来做 浏览器 地址 解析的
2.api:
parse : String --> Object
format: Object —> String
resolve: url拼接
3. 完整的url构成:
https: // www.web-yyb.top: 8080 / vue / index.html ? a=1&b=2#a=10
名词解释:
协议: https
域名: www.web-yyb.top
端口: 8080
路径: www.web-yyb.top: 8080 / vue / index.html
查找字符串: a=1&b=2
哈希: #a=10
querystring
1.进行string 和 object 的格式的转化
2.功能类似于JSON.parse || JSON.stringify
3.api:
parse
stringify Object —> String
escape
unescape
4.名词解释:
encoding 编码
unencoding 解码
escape 中文编码
unescape 中文解码
http-get:
1.get方法格式:
http.get(url,callback)
chunk (分片)
2.try{} catch{} 高级编程 错误信息捕获。
3.实例:
const http = require('http')
http.get('http://api.douban.com/v2/movie/in_theaters',function( res ){
//错误信息的报出
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
//数据处理
res.setEncoding('utf8'); // 数据的编码格式
let data = '' //保存数据
// res.on() // 事件执行
res.on('data',(chunk)=>{
data+=chunk; //将数据流累加起来
})
res.on('end',()=>{
try{
console.log( data )
}catch(e){
console.error( e.message )
}
})
}).on('error',(e)=>{
console.error(`Got error: ${e.message}`);
})