1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| const http = require('http') const fs = require('fs') const furl = require('url') const path = require('path') const httpProxy = require('http-proxy') const proxy = httpProxy.createProxyServer({ target: 'http://192.168.115.246:8081', changeOrigin: true }) const PORT = 9977 const MIME = { 'css': 'text/css', 'gif': 'image/gif', 'html': 'text/html', 'ico': 'image/x-icon', 'jpeg': 'image/jpeg', 'jpg': 'image/jpeg', 'js': 'text/javascript', 'json': 'application/json', 'pdf': 'application/pdf', 'png': 'image/png', 'svg': 'image/svg+xml', 'swf': 'application/x-shockwave-flash', 'tiff': 'image/tiff', 'txt': 'text/plain', 'wav': 'audio/x-wav', 'wma': 'audio/x-ms-wma', 'wmv': 'video/x-ms-wmv', 'xml': 'text/xml' }
proxy.on('error', function (err, req, res) { if (err) { res.writeHead(500, { 'Content-Type': 'text/html' }) res.write('An error occurred in ' + req.url) } res.end() })
http.createServer(function (request, response) { let url = request.url if (isNeedProxy(url)) { proxy.web(request, response) return } let pathName = furl.parse(request.url).pathname let filePath = path.join(__dirname, pathName) let extName = path.extname(filePath).replace('.', '') let contentType = MIME[extName] if (!contentType) { response.writeHead(200, { 'Content-Type': 'text/plain' }) response.write('Not defined mime type') response.end() return } fs.readFile(filePath, function (err, data) { if (err) { response.writeHead(404, { 'Content-Type': 'text/html' }) response.write('The request was not found on this server') } else { response.writeHead(200, { 'Content-Type': contentType }) response.write(data, 'binary') } response.end() }) }).listen(PORT)
function isNeedProxy (url) { return url.indexOf('dev=proxy') > -1 }
console.log('Server is running in http://localhost:' + PORT)
|