本文实例讲述了nodejs实现的简单web服务器功能。分享给大家供大家参考,具体如下:
前端js代码:
<script src="/UploadFiles/2021-04-02/jquery-1.12.1.js">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程序设计有所帮助。