快捷搜索: 王者荣耀 脱发

nodejs搭建web服务器(简单代理)

前端获取数据时经常会遇到跨域问题,用 nginx 做反向代理就可以解决此问题。但是 nginx 属于中间件代理,不同开发者布署的 web 服务器地址可能不一样,这样 nginx 的配置就不能做到通用了。

如果能有一个客户端代理,随着项目源代码提交,这样就可以免去不同开发者的代理配置。webpack-dev-server 就是这样的一个客户端代理,但是如果项目没有用到 webpack,那就没办法用了。那能不能仿照写了一个简单的 web 服务器,用于非 webpack 的项目呢。答案是肯定的,费话少说,上代码。

const request = require(request);
const express = require(express);
const path = require(path);

const app = express();

// 代理配置
const proxyTable = {  
    /api: {
        target: http://localhost/api 
    }
};
app.use(function(req, res,next) {  
    const url = req.url;  
    if (req.method == OPTIONS) {      
      console.log(options_url: , url); 
      
       //  设置cors 跨域
      // res.header("Access-Control-Allow-Origin", req.headers.origin || *);
      // res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
      // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

      // 设置 cookie
      // res.header("Access-Control-Allow-Credentials", true);
      
      res.status(200).send(OK);     
      return;
    } 
    // console.log(req_url: , url);
    next();
});

// 设置静态目录
app.use(express.static(path.join(__dirname, static)));

app.use(/, function(req, res) {  
      const url = req.url; 
      const proxy = Object.keys(proxyTable);  
      let not_found = true; 
      for (let index = 0; index < proxy.length; index++) {    
          const k = proxy[index];    
          const i = url.indexOf(k);   
          if (i >= 0) {     
              not_found = false;     
              const element = proxyTable[k];      
              const newUrl = element.target + url.slice(i+k.length);
              req.pipe(request({url: newUrl, timeout: 60000},(err)=>{
                  if(err){          
                      console.log(error_url: , err.code,url);           
                      res.status(500).send();
                  }     
              })).pipe(res);      
              break;
          } 
      }  
      if(not_found) {    
          console.log(not_found_url: , url);
          res.status(404).send(Not found);
      } else {    
          console.log(proxy_url: , url);
      }
});

// 监听端口      
const PORT = 8080;
app.listen(PORT, () => {  
    console.log(HTTP Server is running on: http://localhost:%s, PORT);
});

PS:static 放静态页面

经验分享 程序员 微信小程序 职场和发展