微信小程序 Node.js (基础十二) GET/POST请求

来源:互联网 发布:citra 3ds模拟器 mac 编辑:程序博客网 时间:2024/05/29 18:59
var http = require("http")var url = require("url")var util = require("util")var querystring = require("querystring")function start(){    //    获取GET请求内容    this.getRequest = function(){        http.createServer(function(request,response){            var pathname = url.parse(request.url).pathname            console.log(pathname)            response.writeHead(200,{"Content-Type":"text/plain"})            response.write("Hello World")            // http://127.0.0.1:8888/user?name=12456            // util.inspect(object) 将任意对象转换 为字符串            // url.parse 将一个URL字符串转换成对象并返回            response.end(util.inspect(url.parse(request.url,true)));            response.end(url.parse(request.url,true).query.name);        }).listen(8888)    }    //    获取POST请求内容    this.postRequst = function (){        http.createServer(function (req, res) {          var body = "";          req.on('data', function (chunk) {            body += chunk;          });          req.on('end', function () {            // 设置响应头部信息及编码            res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});            //  {"name":"123","address":"123123"}            console.log(body)            //  querystring.parse 将一个字符串反序列化为一个对象            //  { '{"name":"123","address":"123123"}': '' }            console.log(querystring.parse(body))            //  JSON.parse(string)  将字符串转为JS对象。            //  JSON.stringify(obj) 将JS对象转为字符串。            //  { name: '123', address: '123123' }            console.log(JSON.parse(body))            body = JSON.parse(body)                res.write("网站名:" + body.name);                res.write("<br>");                res.write("网站 URL:" + body.address);            res.end();          });        }).listen(3000);    }}module.exports = start
var Util = require("./util")var util = new Util ();util.postRequst();