This article mainly introduces the simple web server functions implemented by nodejs, and analyzes the related monitoring, response, data processing and other operating techniques of nodejs to build a web server in the form of examples. Friends who need it can refer to it. I hope it can help everyone. .
Front-end js code:
<script src="jquery-1.12.1.js"></script> <script type="text/javascript"> $.ajax({ url:'http://192.168.0.114:3000',//服务器地址 type:'post', timeout:30, dataType:'json', data:{ "username":username, "password":password }, success:function(res){ console.log(JSON.stringify(res)); }, err:function(err){ alert(err); } });
nodejs code:
var http = require('http'); var url = require('url'); var qs = require('querystring'); http.createServer(function(req,res){ res.writeHead(200,{'Content-Type':'text/plain;charset=UTF-8','Access-Control-Allow-origin':'*'}); if(req.method.toUpperCase() == 'GET'){ var query = url.parse(req.url, true).query;// 接受的数据 res.end(JSON.stringify(query)); }else if(req.method.toUpperCase() == 'POST'){ var postData = ''; req.on('data',function(data){ postData += data; //接受的数据 }); req.on('end',function(){ var query = qs.parse(postData); res.end(JSON.stringify(query));//返回的数据 }); } }).listen('3000',function(){ console.log('this is callback'); }); console.log('server is running');
Related recommendations:
Tutorial on how to build a simple web server using node.js
The above is the detailed content of How to implement simple web server functions in nodejs. For more information, please follow other related articles on the PHP Chinese website!