实时监控node服务的内容变化
http模块是nodeJS的核心模块。它可以创建客户端(倡议请求)和处事端(监听请求)。
1. 客户端client应用:
1. 爬虫
2. 中间层-解决跨域问题
let http = require(‘http‘);
// 处事端发送的请求不存在跨域问题
let client = http.request({
hostname: ‘localhost‘,
port: 3000,
path: ‘/aaa?name=lyra‘,
method: ‘POST‘,
headers: {
‘Content-Type‘: ‘application/x-www-form-urlencoded‘
}
}, function(response) {// response可读流
response.on(‘data‘, function(data) {
console.log(JSON.parse(data.toString()));
})
});
// client相当于可写流
client.end("a=1&b=2");// 发送请求体
let http = require(‘http‘); let querystring = require(‘querystring‘); let url = require(‘url‘); let server = http.createServer(function(request, response) {// 监听函数;请求到来时触发 /////////// request-->可读流 /****1. 请求行***/ console.log(request.method.toLowerCase());// 大写 console.log(request.url); // 端标语后面的部分;不包罗hash; eg: /aaa?a=b const {pathname, query} = url.parse(request.url, true); // true暗示解析成东西 // pathname: /aaa query: {a: ‘b‘} console.log(request.httpVersion); /****2. 请求头***/ //console.log(request.headers); // 所有属性名小写 /****3. 请求体***/ // 请求体通过监听data获取;on监听的回调是异步执行 let arr = []; request.on(‘data‘, function(data) {// 只有请求体有内容,才会触发 arr.push(data); }); request.on(‘end‘, function(err) { // 岂论请求体是否有内容,,总会触发 let content = Buffer.concat(arr).toString(); // username=lyra // 可写流的参数只能是字符串和buffer if (request.headers[‘content-type‘] === ‘application/x-www-form-urlencoded‘) { let result = JSON.stringify(querystring.parse(content));// =parse(content, ‘&‘, ‘=‘) /////////// response-->可写流(字符串或者Buffer) /******1. 响应行 */ response.statusCode = 200; // 必需是有效状态码 /******2. 响应头 */ response.setHeader(‘Content-Type‘, ‘application/json‘); /******3. 响应体 */ // end前面还可以使用write要领 response.end(result); //当即触发;应该安排在end回调中 } }) }); // 监听特定的端口和IP /** * 端标语最大65535;一般使用3000+的端口,因为很多会被占用 */ server.listen(3000, ‘localhost‘, () => { console.log(‘3000 started‘); })
3. nodemonnode monitor。实时监控node处事的内容变革,自动重启处事。
命令:
nodemon 具体文件
4. curl屈从令行倡议http请求
// 通过命令行倡议http请求 // GET curl -v http://localhost:3000 //-v检察信息 // POST curl -v -X POST -d "username=lyra"//localhost:3000 //-X 指定请求方法 -d 指定通报数据 // 带请求头 curl -v --header "Range:bytes=0-3" http://
node-http创建处事端和客户端
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31725.html