首页 / 更多教程 / node-http创建服务端和客户端
node-http创建服务端和客户端
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了node-http创建服务端和客户端,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2368字,纯文字阅读大概需要4分钟。
内容图文
![node-http创建服务端和客户端](/upload/InfoBanner/zyjiaocheng/647/dbf1126879f649588b2927b10bbb2b18.jpg)
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");// 发送请求体
2. 服务端server
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. nodemon
node 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://www.baidu.com
内容总结
以上是互联网集市为您收集整理的node-http创建服务端和客户端全部内容,希望文章能够帮你解决node-http创建服务端和客户端所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。