利用http-proxy实现本地化前端项目dist目录预览

背景

先后端分离项目,前端发布基本是在服务器放置一个目录,而后经过 nginx 代理方式,经过监听 / 跳转到前端dist目录存放的路径下的index.html。javascript

server{
    location / {
        gzip  on;
        add_header Cache-control no-cache;
        root 前端dist目录存放的路径;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}
复制代码

前端发起的后端服务基本都是走 /api 路径走的,因此还须要配置一个监听/api距离css

location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_pass http://api.test.cn; // 跳转到后台的api服务器
    }
复制代码

解决方案

若是想在本地配置一套相似服务器端的环境。html

var config = {
  target: '服务器端的地址',
  port: 3001, // 本地server 的port
  host: '0.0.0.0', // 本地server 的host
  dir: '../dist', // 监听dist 目录
  prefix: '/api', // 服务器端的api 接口 前缀
  debug: true // 是否开启本地日志。
};

复制代码

主要借助于 http-proxy 这个库实现接口的转发服务。前端

经过 http.createServer 建立本地服务java

经过解析请求URL的路径,而后根据config.prefix 进行匹配,若是包含prefix ,若是匹配成功了,就直接调用 http-proxy 走转发走。nginx

http.createServer(function (request, response) {
 // 获取请求url 的 path
  var pathName = url.parse(request.url).pathname;

    // 走转发走
  if (pathName.indexOf(config.prefix) === 0) {
    config.debug && console.log(`Rewriting path from "${pathName}" =====> to "${proxyConfig.target}${pathName}"`);
    proxy.web(request, response, proxyConfig);
    return;
  }
    
})
复制代码

不然经过拦截是否静态资源路径 static 若是不是,则直接跳转到 index.htmlgit

if (pathName.indexOf('static') === -1) {
    pathName = '/index.html';
  }
复制代码

先经过fs.exists 查看文件是否存在,若是不存在,就返回404.github

realName = path.join(__dirname, config.dir, pathName);
  // 判断文件是否存在。
  fs.exists(realName,function(exists){
    // 不存在直接返回 404
      if(!exists){
          response.writeHead(404, {'Context-type': 'text/plain'});
          response.write('this request url ' + pathName + ' was not found on this server.');
          response.end();
          return;
      }
      
  })
复制代码

后续的静态资源就经过文件读取的方式获取fs.readFile 返回给浏览器端就好了。web

基本的文件类型后端

var requestType = {
  "css": "text/css",
  "js": "text/javascript",
  "html": "text/html"
};
复制代码

文件读取。

fs.readFile(realName, 'binary', function (err, file) {
    if (err) {
      response.writeHead(500, {'Context-type': 'text/plain'});
      response.end(err);
    } else {
      var contentType = requestType[ext] || "text/plain";
      response.writeHead(200, {'Context-type': contentType});
      response.write(file, 'binary');
      response.end();
    }
});
复制代码

经过这样的配置就能够在本地实现dist目录的预览功能了。

github

github.com/bosscheng/d…

相关文章
相关标签/搜索