node.js轻松搭建一个服务器

前端获取数据时经常遇见跨域问题,以前一直用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 });
    原文作者:前端爱好者
    原文地址: https://segmentfault.com/a/1190000017149729
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞