nodejs实现的简单web服务器功能示例
本文实例讲述了nodejs实现的简单web服务器功能。分享给大家供大家参考,具体如下:
前端js代码:
<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代码:
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');
希望本文所述对大家nodejs程序设计有所帮助。
相关推荐
seanzed 2020-10-15
swazerz 2020-05-16
raksmart0 2020-08-17
boneix 2020-10-21
ifconfig 2020-10-14
学留痕 2020-09-20
往后余生 2020-09-17
kka 2020-09-14
redis 2020-09-07
lzccheng 2020-09-06
soyo 2020-08-31
stonerkuang 2020-08-18
LxyPython 2020-08-17
Lzs 2020-08-14
MrHaoNan 2020-07-31
80530895 2020-07-05
lengyu0 2020-06-28
YarnSup 2020-06-28