[转] nodeJS的post提交简单实现

index.js:

1
2
3
4
5
6
7
8
var server = require('./server');
var router = require('./route');
var requestHandler = require('./requestHandler');
var hander = {};
hander['/'] = requestHandler.start;
hander['/start'] = requestHandler.start;
hander['/upload'] = requestHandler.upload;
server.starts(router.router, hander);

server.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var http = require('http');
var url = require('url');
function start(router, hander) {
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        var postData = "";
        request.setEncode = "utf8";
        request.addListener('data', function(postDataChunk){
            postData += postDataChunk;
        })
        request.addListener('end', function(){
            router(pathname, hander, response, postData);
        })
    }
    http.createServer(onRequest).listen(8080);
}
exports.starts = start;

route.js:

1
2
3
4
5
6
7
8
9
function route(pathname, handler, response, postData) {
    if (typeof(handler[pathname]) === 'function') {
        handler[pathname](response, postData);
        return true;
    } else {
        return false;
    }
}
exports.router = route;

requestHandler.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var querystring = require("querystring");
function start(response) {
    var body = '<html>' + '<head>' + '<meta http-equiv="Content-Type" content="text/html; ' + 'charset=UTF-8" />' + '</head>' + '<body>' +
    '<form action="/upload" method="post">' + '<textarea name="text" rows="20" cols="60"></textarea>' + '<input type="submit" value="Submit text" />'
+    '</form>' + '</body>' + '</html>';
    response.write(body);
    response.end();
}
function upload(response, postData) {
    response.write("You've sent: " + querystring.parse(postData).text);
    response.end();
}
exports.start = start;
exports.upload = upload;

访问localhost:8080/start或者localhost:8080;输入数据,提交即可。

上一篇:Keepalived 配置和使用


下一篇:Nginx实战部署常用功能演示(超详细版),绝对给力~~~