Node.js GET/POST请求

获取GET请求内容

var http = require('http');

var url = require('url');

var util = require('util');

http.createServer(

          function(req, res){

                              res.writeHead(200, {

                                       'Content-Type': 'text/plain;charset=utf-8'

                            });

                             res.end(util.inspect(url.parse(req.url, true)));

}).listen(3000);//监听的端口号

参数都在 url.parse(req.url, true).query;里面

获取post请求内容

post请求的内容都在请求体中

http.createServer(function (req, res) {
    // body,用于暂存请求体的信息
    var body = "";
    // 通过req的data事件监听函数,每当接受到请求体的数据,存到body
    req.on('data', function (chunk) {
        body += chunk;
    });
    // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回
    req.on('end', function () {
        // 解析参数
        body = querystring.parse(body);
        // 设置响应头部信息及编码
        res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});

        if(body.name && body.url) { // 输出提交的数据
            res.write("网站名:" + body.name);
            res.write("<br>");
            res.write("网站 URL:" + body.url);
        } else {  // 输出表单
            res.write(postHTML);
        }
        res.end();
    });
}).listen(3008);




原文地址:https://www.cnblogs.com/joer717/p/10521877.html