首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >代理的咕噜问题- Gruntjs

代理的咕噜问题- Gruntjs
EN

Stack Overflow用户
提问于 2013-11-15 20:49:38
回答 1查看 2K关注 0票数 1

我一整天都在努力让我的代理建立在我的Gruntfile中。这是我的Gruntfile

代码语言:javascript
复制
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']);
};

当我运行我的grunt server时,我只能访问代理。如果我只想点击代理以外的任何东西,我就会得到一个404。这个问题是怎么回事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-07 17:59:59

我在使用grunt-connect-proxy设置代理时也遇到了很多困难。

深入研究grunt-contrib-connect的源代码,我意识到它使用了场景背后的nodeJs Connect框架。

在内部,middleware选项默认为此函数:

代码语言:javascript
复制
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;
}

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

知道了这一点,我们就可以像这样使用proxy-middleware nodeJs包了:

代码语言:javascript
复制
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.
                ];
            }
        }
    }
}

基本上,我们正在向中间件数组中添加一个中间件。这个新的代理中间件将把任何传入的请求(如http://localhost:9002/api/ )转换为http://localhost:8080/

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20010335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档