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