nodejs实现的简单接口

//需要下载引用的 model
var http = require('http');
var url = require('url');

//创建服务器
var server = http.createServer(function(req, res) {
    var pathname = url.parse(req.url).pathname;
   //这里是获取请求的来源:比如访问来源为http://localhost:443/text.html 会得到/text.html,所以这里可以用pathname来判断来自不同访问来源来做响应操作
    res.writeHead(200, {'Content-type': 'text/html'});
    var url_info = require('url').parse(req.url, true);
   
    if (pathname == "/index.html") {
//接收get提交过来的参数,自己将对方的数据进行对应操作
var post_data = require('querystring').stringify(url_info.query);
console.log('参数:'+post_data);
       //这里返回json数据
res.writeHead(200, {"Content-Type": "application/json"});
        var otherObject = { A1: "a1", B1: "b1" };
        var otherArray = ["a", "b"];
        var json = JSON.stringify({
            anObject: otherObject,
            anArray: otherArray,
         });
        console.log(JSON.stringify(json));
        res.end(json);
  });  
    } else if(pathname=="/text.html") {
        //返回网页数据
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write('<head><meta charset="utf-8"/></head>');
        res.write('<h1>Node.js</h1>');
        res.write('<b>亲爱的,你慢慢飞,小心前面带刺的玫瑰...</b>');
        res.end('<p>Hello World</p>');
    }


//这个方法可以捕捉POST请求
    req.addListener('data', function (chunk) {
//chunk就是对方post提交的参数
        console.log('post提交数据:' + chunk);
//进行相应数据操作后,返回数据
res.writeHead(200, {"Content-Type": "application/json"});
        var otherObject = { item1: "item1val", item2: "item2val" };
        var otherArray = ["item1", "item2"];
        var json = JSON.stringify({
            anObject: otherObject,
            anArray: otherArray,
         });
        console.log(JSON.stringify(json));
        res.end(json);
  });  
    });
}).listen(443, function() {
    console.log('Listening at: http://localhost:443');

});



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值