這個方法僅是概念.. 在後續管理上會有很多的問題..
**有用mime模組,要先 npm i mime
var http = require('http');
var fs= require('fs');
var mime = require('mime');
var path = require('path');
var url = require('url');
http.createServer(function(req,res){
var urls = url.parse(req.url);
var relpath = path.join(__dirname,urls.pathname);
if(urls.pathname == "/hello"){
res.writeHead(200,{'Content-Type':'text/html'});
res.end('<html><body>hello</body></html>');
}else{
fs.readFile(relpath,function(err,data){
if(err){
console.log("bad");
res.writeHead(404,'');
res.end("request not found");
}else{
res.writeHead(200,{'Content-Type':mime.lookup(relpath),'Content-Length':data.length});
res.end(data);
}
});
}
}).listen(80,'127.0.0.1',function(){
console.log("Server run as 127.0.0.1:80");
});
輸入localhost/hello 應該會出現
可能要考慮GET, POST, DELETE ,PUT,HEAD,MAP 的實現
參考:
http://ithelp.ithome.com.tw/question/10078021
沒有留言:
張貼留言