从零学习node.js之搭建http服务器(二)

2020-06-17 06:06:00易采站长站整理


// server.js
var http = require('http'),
url = require('url');

http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
console.log(pathname);
response.end();
}).listen(3000);
console.log('server has started...');

我们任意改变URL地址,会看到输出的每个地址的pathname(忽略/favicon.ico):


http://127.0.0.1:3000/ // 输出: /
http://127.0.0.1:3000/show/ // 输出: /show/
http://127.0.0.1:3000/show/img/ // 输出: /show/img/
http://127.0.0.1:3000/show/?username=wenzi // 输出: /show/

因此我们就根据pathname进行路由,对路由进行方法映射:


// server.js
var http = require('http'),
url = require('url'),
starter = require('./starter'),
uploader = require('./uploader');

http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
var routeurl = {
'/' : starter.start,
'/show' : uploader.upload
}

if( typeof routeurl[pathname]=== 'function' ){
routeurl[pathname](request, response);
}else{
console.log('404 not found!');
response.end();
}
}).listen(3000);
console.log('server has started...');

如果匹配到路由 / ,则执行

starter.start(request, response) 
;如果匹配到路由 /show ,则执行
uploader.upload(request, response) 
。如果都没匹配到,则显示404。

四、 图片上传并显示

在上面我们已经能成功提交数据了,这里来讲解如何进行图片上传并显示。使用node自带的模块处理起来非常的麻烦,这里我们使用别人已经开发好的formidable模块进行编写,它对解析上传的文件数据做了很好的抽象。


npm install formidable --save-dev

在starter.js中,我们添加上file控件:


// starter.js
function start(request, response){
var html = '<html>
<head>
<meta charset=UTF-8" />
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<p>file : <input type="file" name="upload" multiple="multiple" /></p>
<p><input type="submit" value="submit" name="submit" /></p>
</form>
</body>
</html>';

response.writeHead(200, {"Content-Type":"text/html"});
response.write( html );
response.end();
}
exports.start = start;

4.1 图片上传

首先我们进行的是图片上传操作,首先我们要确保当前目录中存在tmp和img目录。