代理人的Grunt问题 - Gruntjs

jha*_*amm 1 javascript gruntjs

我一直在努力尝试在我的Gruntfile中设置我的代理.这是我的Gruntfile:

var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

module.exports = function(grunt) {

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  grunt.initConfig({
    connect:{
      livereload: {
        options: {
          middleware: function (connect) {
            return [proxySnippet];
          }
        }
      },
      options: {
        port: 9000,
        base: 'app',
        keepalive: true,
        livereload: true
      },
      proxies: [
        {
          context: '/public/api',
          host: 'localhost',
          port: 8182,
          https: false,
          rewrite: {
            '^/public/api': ''
          }
        }
      ]
    }
  });

  grunt.registerTask('server', ['less', 'configureProxies', 'connect', 'connect', 'watch', 'open:dev']);
};
Run Code Online (Sandbox Code Playgroud)

当我运行我的时候grunt server我只能打我的代理.如果我试着点击代理以外的任何东西我得到一个404.是什么给了我这个问题?

Tim*_*nin 5

使用grunt-connect-proxy设置代理也遇到了很多麻烦.

挖掘grunt-contrib-connect的源代码,我意识到它使用场景后面的nodeJs Connect框架.

在内部,该middleware选项默认为此功能:

function (connect, options) {
    var middlewares = [];
    if (!Array.isArray(options.base)) {
        options.base = [options.base];
    }
    var directory = options.directory || options.base[options.base.length - 1];
    options.base.forEach(function (base) {
        // Serve static files.
        middlewares.push(connect.static(base));
    });
    // Make directory browse-able.
    middlewares.push(connect.directory(directory));
    return middlewares;
}
Run Code Online (Sandbox Code Playgroud)

这基本上将connect.staticconnect.directory中间件添加到传递给connect(middlewares)构造函数的数组中.

知道了,我们可以像这样使用代理中间件 nodeJs包:

connect: {
    server: {
        options: {
            port: 9002,
            keepalive: true,
            middleware: function (connect, options) {
                // Proxy all requests to target the local application.
                var proxyOptions = require('url').parse('http://localhost:8080/');
                proxyOptions.route = '/api';
                return [
                    require('proxy-middleware')(proxyOptions), // Include the proxy first.
                    connect.static(options.base), // Serve static files.
                    connect.directory(options.base) // Make empty directories browse-able.
                ];
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上我们正在向中间件阵列添加中间件.这种新的代理中间件将翻译任何传入的请求像http://localhost:9002/api/http://localhost:8080/