nodeJS的post提交简单实现

index.js:

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:
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:
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:
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;输入数据,提交即可。

你可能感兴趣的:(nodeJS的post提交简单实现)