30天学习日记
仅用于个人的学习记录和总结,如果有什么地方写错或理解错,有幸被发现,欢迎指正。
Day2
- Nodejs 搭建静态文件服务器(超简陋,未完成)
Nodejs 搭建静态文件服务器(超简陋,未完成)
在昨天的基础上,想实现rest,仅仅分了三个类型
但是在实际测试中,图片总是无法显示,原因还没找到,太晚了,先休息了。
↓ 这是fileServer.js ↓
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var queryString = require('querystring');
// var morgan = require('morgan');
var fileServer = http.createServer(function(req,res){
console.log("Request port 3001 ");
//获取请求地址
var requrl = req.url;
var urlparse = url.parse(requrl);
//请求路径
var pathname = urlparse.pathname;
//pathname+参数
// var urlpath = urlparse.path;
//参数
var query = urlparse.query;
//后缀
var suffix = path.extname(pathname);
console.log("requrl "+requrl);
console.log("urlparse "+urlparse);
console.log("pathname "+pathname);
console.log("query "+query);
console.log("suffix "+suffix);
staticFileReq(res, pathname, suffix);
}).listen(3001,"127.0.0.1");
//解析静态请求
function staticFileReq(response, pathName, suffixStr) {
//读取静态文件并生成流
fs.readFile(pathName.substr(1), function(err, data) {
if (err) {
console.log(err);
//HTTP 404 :页面不存在
//没找到对应的静态文件怎么办,给个404错误
response.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' });
//响应文件流
response.write("页面不存在!404");
response.end();
} else {
//HTTP 200 : 成功
if (suffixStr === ".jpg") {
//设置charset=utf-8防止乱码
response.writeHead(200, { 'Content-Type': 'image/jpeg'});
} else if (suffixStr === ".css") {
response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
} else {
response.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
}
//响应文件流
response.write(data.toString());
response.end();
}
});
}
fileServer.once('listening',function(){
console.log('Server running at http://127.0.0.1:3001/');
});
↓ 这是index.html ↓
<!DOCTYPE>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
</style>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/common.js"></script>
<script language="JavaScript" type="text/javascript">
</script>
</head>
<body>
<div id = "StaticFilesArea">
<img id="imageL" src="/image/123.jpg"border =0 style="width:100%;height:100%;"/>
</div>
</body>