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 in need can refer to it
The example in this article describes the simple web server function implemented by nodejs. Share it with everyone for your reference, the details are as follows:
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');
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to perfectly parse data in js
Solve the problem of failure after using vue.js routing
The above is the detailed content of Simple web server function example implemented by nodejs. For more information, please follow other related articles on the PHP Chinese website!