node.js輕鬆搭建一個伺服器

前端愛好者發表於2019-01-19

前端獲取資料時經常遇見跨域問題,以前一直用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: ` 
10   }
11 };交流學習圈582735936
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   }交流學習圈582735936
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
66 });

相關文章