1

In one webapp that I'm working with, I have deal with URLs like the one below:

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

This value.with.periods is a URL param, like the ones that you declare on angular's routeProvider:

angular.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/section/:param', {
            templateUrl: 'url-to-template',
            controller: 'ExampleCtrl',
            resolve: {
                ...
            }
        });
}]);

The problem is that the server used, running under Grunt tasks, cannot handle URLs with periods in it:

Cannot GET /section/value.with.periods

I'm running Grunt with grunt-contrib-proxy and connect-modrewrite, and the livereload task, which configures the connect-modrewrite, is the one below:

        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;
                }
            }
        }

I need to be capable to deal with URLs with periods on the params used on Angular. Any help will be appreciated.

Thanks.

4

1 回答 1

2

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

^[^\\.]*$

这意味着:将 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]']));

这给出了预期的结果。有关更多信息,请参阅评论。

于 2015-01-20T22:43:54.707 回答