温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

nodejs如何搭建web服务器

发布时间:2020-12-05 11:29:37 来源:亿速云 阅读:108 作者:小新 栏目:web开发

小编给大家分享一下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服务器有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI