Grunt: Location URL app with period

Grunt: Location URL app with period

在我正在使用的一个网络应用程序中,我处理了 URL 如下所示:

http://localhost:8080/section/value.with.periods

这个 value.with.periods 是一个 URL 参数,就像您在 angular 的 routeProvider:

上声明的参数一样
angular.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/section/:param', {
            templateUrl: 'url-to-template',
            controller: 'ExampleCtrl',
            resolve: {
                ...
            }
        });
}]);

问题是在 Grunt 任务下使用的服务器 运行 无法处理 URL 中带有句点的内容:

Cannot GET /section/value.with.periods

我是 运行 Grunt grunt-contrib-proxyconnect-modrewrite,配置 connect-modrewritelivereload 任务如下:

        livereload: {
            options: {
                open: 'http://localhost:<%= connect.options.port %>',
                base: [
                    '.tmp',
                    '<%= config.app %>'
                ],
                middleware: function(connect, options) {
                    if (!Array.isArray(options.base)) {
                        options.base = [options.base];
                    }

                    // Setup the proxy
                    var middlewares = [proxySnippet];

                    var modRewrite = require('connect-modrewrite');
                    middlewares.push(modRewrite(['^[^\.]*$ /index.html [L]']));
                    // middlewares.push(modRewrite(['!\.html|\.js|\.svg|\.css|\.png|\.jpg\.gif|\swf$ /index.html [L]']));


                    // Serve static files.
                    options.base.forEach(function(base) {
                        middlewares.push(connect.static(base));
                    });

                    // Make directory browse-able.
                    var directory = options.directory || options.base[options.base.length - 1];
                    middlewares.push(connect.directory(directory));

                    return middlewares;
                }
            }
        }

我需要能够在 Angular 上使用的参数上处理带有句点的 URL。任何帮助将不胜感激。

谢谢。

您的重写正则表达式排除了所有带有句点的路径:

^[^\.]*$

这意味着:将 url 与所有字符匹配,除非它们有反斜杠或句点。所以 /section/value.with.periods 将被忽略。

您应该将正则表达式更改为更宽容的内容:

middlewares.push(modRewrite(['^(.*)$ /index.html [L]']));

你应该可以开始了。

编辑解决方案:

在评论中我们得出了答案:上面的正则表达式会将所有 url 重写为 index.html,导致其他文件无法提供。有一条注释掉的行仅重写具有未知文件扩展名的 url:

middlewares.push(modRewrite(['!\.html|\.js|\.svg|\.css|\.png|\.jpg|\.gif|\.swf$ /index.html [L]']));

这给出了预期的结果。查看评论了解更多信息。