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

背景

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

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

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

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服务器
    }

解决方案

如果想在本地配置一套类似服务器端的环境。

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 创建本地服务

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

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.html

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

先通过fs.exists 查看文件是否存在,如果不存在,就返回404.

  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 返回给浏览器端就行了。

基本的文件类型

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

https://github.com/bosscheng/dist-local-preview

猜你喜欢

转载自blog.csdn.net/wancheng815926/article/details/106115126