当前位置: 首页 > 后端技术 > Node.js

Node.js学习记录_0

时间:2023-04-04 00:42:00 Node.js

最近在深入学习,争取尽快掌握Node.js的技术细节。考虑开篇文章记录下需要记录的概念、方法和代码示例,方便在实际项目中查找。本文将持续更新,或另开一篇文章讨论更多核心关键技术问题。这是通过http模块进行客户端-服务器通信的基本示例。个人觉得很不错,虽然有些地方需要重构,还是先记录一下吧。//Clientvarhttp=require('http');varqs=require('querystring');functionsend(theName){http.request({host:'127.0.0.1',port:3000,url:'/',method:'POST'},function(res){res.setEncoding('utf8');res.on('end',function(){console.log('\nRequestcompleted!');process.stdout.write('\nyourname:')})}).end(qs.stringify({name:theName}));}process.stdout.write('\nyourname:');process.stdin.resume();process.stdin.setEncoding('utf8');process.stdin.on('data',function(name){send(name.replace('\n',''))});//Servervarhttp=require('http');varqs=require('querystring');http.createServer(function(req,res){varbody='';req.on('data',function(chunk){body+=块;});req.on('end',function(){res.writeHead(200);res.end('Done');console.log('\ngotname:'+qs.parse(body).name+'\n');})}).listen(3000);console.log('服务器运行在端口:3000');varhttp=require('http');varqs=require('querystring');http.createServer(function(req,res){if('/'===req.url){res.writeHead(200,{'Content-Type':'text/html'});res.end([`

我的表单

你叫什么名字?

`.join(''));}elseif('/url'===req.url&&'POST'===req.method){varbody='';req.on('data',function(chunk){body+=chunk;});req.on('end',function(){res.writeHead(200,{'Content-Type':'文本/html'});res.end('你的名字是'+qs.parse(body).name+'

')})}else{res.writeHead(404);res.end('未找到');}}).listen(3000);console.log('服务器运行在端口:3000');