Node.js http.createServer 简单服务配置

发布时间:2019-04-05 14:00:12发布者:Mr.Zhang阅读(286)

基本实现:

var http = require("http");
var server = http.createServer(function (req, res) {
    if (req.url == "/") {
        res.end("Hello world!");
    }
});

server.listen(8000);

解析GET参数:

var http = require("http");
var qs = require("querystring");

var server = http.createServer(function (req, res) {

    var urlObj = url.parse(req.url);
    var query = urlObj.query;
    var queryObj = querystring.parse(query);
    if (req.url == "/") {
        res.end("Hello world!" + " " +queryObj.user);
    }
});

server.listen(8000);

解析POST:

var http = require("http");

var server = http.createServer(function (req, res) {

    if (req.url == "/") {
        req.on('data', function (chunk) {
            body += chunk;
        });

        req.on('end', function () {
            body = JSON.parse(body);
            res.end("Hello world!" + " " +body.user);
        });
    }
});

server.listen(8000);

 





本文转自博客园,原文地址:https://www.cnblogs.com/yamboo/p/10658309.html