百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> nodejs搭建web效劳器的办法
分享文章到:

nodejs搭建web效劳器的办法

发布时间:09/01 来源:未知 浏览: 关键词:
本篇文章给大家带来的内容是关于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 放静态页面

以上就是nodejs搭建web效劳器的办法的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有150人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板