nodejs之http模組對路由的處理
阿新 • • 發佈:2018-12-21
const http = require('http'); const fs = require('fs'); const Mime = require('./libs/Mime');//這個是處理content-type的庫 let users = [ { name: 'neal', gender: '女', t: ["shcool","hospital"] }, { name: 'shy', gender: '男', t: ['top'] }, { name: 'faker', gender: '男', t: ['wc',"micky happy house"] } ]; const app = http.createServer( (req, res) => { res.writeHead(200, http.STATUS_CODES[200], { 'Content-Type': 'text/html;charset=utf-8' }); let content = ''; /** * 把動態與靜態資源進行區分:url * 約定:以 /static 開頭的都算是靜態,我約定把靜態檔案都放在了 /static 對應的目錄下 */ // console.log( req.url.startsWith('/static')) if ( req.url.startsWith('/static') ) { staticSend(__dirname + req.url); } else { //動態 switch(req.url) { case '/user': res.writeHead(200, http.STATUS_CODES[200], { 'Content-Type': 'application/json;charset=utf-8' }); let data = users.map( user => user.name ); console.log(data); let data1=JSON.stringify(data) console.log(data1) res.end(data1); break; case '/getbaidu': const r = http.request({ host: 'www.baidu.com' }, function(badiuRes) { let data = ''; badiuRes.on('data', (chunk) => { data += chunk.toString(); //實際情況下是不能進行字串處理的 //因為傳過來的可能是視訊,圖片等 //因此要對buffer進行處理 }); badiuRes.on('end', () => { // console.log('響應中已無資料。'); res.end(data); }); }); r.end(); break; } } function staticSend(filename, headers={'Content-Type': 'text/html;charset=utf-8'}, statusCode=200) { if (fs.existsSync(filename)) { let ext = filename.substring( filename.lastIndexOf('.') + 1 ); if (!ext) { ext = 'txt'; } headers['Content-Type'] = Mime.getType(ext); res.writeHead(statusCode, http.STATUS_CODES[statusCode], headers); content = fs.readFileSync(filename); res.end(content); } else { staticSend(__dirname + '/static/404.html', { 'Content-Type': 'text/html;charset=utf-8' }, 404); } } } ); app.listen(80, () => { console.log('伺服器啟動成功了'); });