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

NodeJs创建一个简单的服务

时间:2023-04-03 19:43:26 Node.js

个人学习记录,仅供参考创建第一个应用参考导入所需模块的步骤:我们可以使用require命令来加载Node.js模块。创建服务器:服务器可以监听客户端请求,类似于Apache、Nginx等HTTP服务器。接收请求和响应请求服务器很容易创建,客户端可以使用浏览器或终端发送HTTP请求,服务器收到请求后返回响应数据。引入所需的模块varhttp=require("http");createserver/***request请求输入-请求信息*response响应输出-输出东西*http模块提供的函数:createServer。此函数返回一个对象,该对象具有名为listen的方法,该方法采用数字参数指定此HTTP服务器正在侦听的端口号。*/http.createServer(function(req,res){switch(req.url){case'/1.html':res.write("1111111");break;case'/2.html':res.write("22222222");中断;默认:res.write("404");中断;}res.end();}).listen(8888);启动服务器nodeserver.js接收前端数据GET前端代码提交表单Username:Password:后台代码接收数据接收数据参数即可三种方式解析手动拆分字符串(比较麻烦)使用node提供的querystring方法consthttp=require('http');constquerystring=require('querystring');http.createServer(function(req,res){varGET={};if(req.url.indexOf("?")!=-1){vararr=req.url.split('?');varurl=arr[0];GET=querystring.parse(arr[1]);}else{varurl=req.url;}console.log(url,GET)///aaa{user:'MonkeyKing',pass:'123456'}res.write('aaa');重发();})。听(8080);使用node提供的url方法(相对来说url比较简单)consthttp=require('http');consturlLib=require('url');http.createServer(function(req,res){varobj=urlLib.parse(req.url,true)varurl=obj.pathname;varGET=obj.query;控制台。log(url,GET)///aaa{user:'MonkeyKing',pass:'123456'}res.write('aaa');res.end();}).listen(8080);POST前台代码提交表单用户名:密码:后台代码接收数据这里我们使用node提供的querystring方法解析接收到的代码上的数据consthttp=require('http');constquerystring=require('querystring');http.createServer(function(req,res){varstr='';//接收数据//data==>每次都有一条数据到达(多次)执行,它被分割一次vari=0;req.on('data',function(data){console.log(`第${i++}个接收到的数据`);//第0个接收到的数据(每次执行都会打印一个)str+=data;});//end==>当所有数据到达时(只发生一次)req.on('end',function(){varPOST=querystring.parse(str);console.log(POST);//{user:'孙悟空',pass:'123123'}});}).listen(8080);以上知识点综合起来consthttp=require('http');constfs=require('fs');constquerystring=require('querystring');consturlLib=require('url');http.createServer(function(req,res){//GETvarobj=urlLib.parse(req.url,true);varurl=obj.pathname;constGET=obj.query;//POSTvarstr='';req.on("data",function(data){str+=data;});req.on("end",function(){constPOST=querystring.parse(str);/***url==>你想要的*GET==>获取数据*POST==>发布数据*/console.log(url,GET,POST);//文件请求varfile_name='./www'+url;fs.readFile(file_name,function(err,data){if(err){res.write('404')}else{res.write(data)}})})}).listen(8080);