处理url的解析
var qureyString = require('querystring');
var server = http.createServer ((req, res) =>{
//http://localhost:8000/start?foo=bar&hello=word
console.log('req.url', req.url); // /start?foo=bar&hello=word
var path = req.url.split('?')[0]; // /start
console.log('path', path);
req.query = qureyString.parse(req.url.split('?')[1]);
var foo = req.query.foo ||''; //bar
var hello = req.query.hello ||''; //word
});
server.listen(8000);
var http = require('http');
var fs = require('fs');
var service = http.createServer((req,res) => {
console.log('req.url', req.url);
if ('GET' === req.method && '/images' === req.url.substr(0,7) && '.jpg' === req.url.substr(-4)){
//处理
fs.stat(__dirname + req.url,(err, stat) => {
if (err || !stat.isFile() ) {
res.writeHead(404);
res.end('not found');
return;
}
console.log('下载图片');
server(__dirname +req.url, 'application/jpg');
});
} else if ('GET' === req.method && '/' === req.url) {
server(__dirname + '/index.html' , 'text/html');
} else {
res.writeHead(404);
res.end('not found');
}
function server (path, type) {
res.writeHead(200,{'Content-Type':type});
fs.createReadStream(path).pipe(res);
}
});
service.listen(8000);