1. 程式人生 > >nodeJS搭一個簡單的(代理)web伺服器

nodeJS搭一個簡單的(代理)web伺服器

前端獲取資料時經常遇見跨域問題,以前一直用nginx做反向代理。最近在用vuejs,發現webpack-dev-server的代理簡單好用。於是仿照寫了一個簡單的web伺服器,用於非webpack的專案。

 1 const request = require('request');
 2 const express = require('express');
 3 const path = require('path');
 4 
 5 const app = express();
 6 
 7 const proxyTable = {
 8   '/wcf': {
 9     target: 'http://localhost/wcf' 
10
} 11 }; 12 13 app.use(function(req, res,next) { 14 const url = req.url; 15 if (req.method == 'OPTIONS') { 16 console.log('options_url: ', url); 17 18 // res.header("Access-Control-Allow-Origin", req.headers.origin || '*'); 19 // res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
20 // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); 21 22 // res.header("Access-Control-Allow-Credentials", true); 23 24 res.status(200).send('OK'); 25 return; 26 } 27 28 // console.log('req_url: ', url); 29 next(); 30 }); 31 32 33 app.use(express.static(path.join(__dirname, 'static')));
34 35 app.use('/', function(req, res) { 36 const url = req.url; 37 const proxy = Object.keys(proxyTable); 38 let not_found = true; 39 for (let index = 0; index < proxy.length; index++) { 40 const k = proxy[index]; 41 const i = url.indexOf(k); 42 if (i >= 0) { 43 not_found = false; 44 const element = proxyTable[k]; 45 const newUrl = element.target + url.slice(i+k.length); 46 req.pipe(request({url: newUrl, timeout: 60000},(err)=>{ 47 if(err){ 48 console.log('error_url: ', err.code,url); 49 res.status(500).send(''); 50 } 51 })).pipe(res); 52 break; 53 } 54 } 55 if(not_found) { 56 console.log('not_found_url: ', url); 57 res.status(404).send('Not found'); 58 } else { 59 console.log('proxy_url: ', url); 60 } 61 }); 62 63 const PORT = 8080; 64 app.listen(PORT, () => { 65 console.log('HTTP Server is running on: http://localhost:%s', PORT); 66 });