14

对于我的本地开发系统,我正在尝试使用 grunt-contrib-connect 服务前端资产。我需要一个在 Firefox 中使用字体的跨域解决方案。服务器运行得很好,但我似乎无法设置标题。

我正在使用 0.7.1 版的 grunt-contrib-connect。

connect: {
        dev: {
            options: {
                port: '9001',
                base: 'build',
                hostname: 'localhost',
                keepalive: true,
                middleware: function(connect, options, middlewares) {
                    // inject a custom middleware into the array of default middlewares
                    // this is likely the easiest way for other grunt plugins to
                    // extend the behavior of grunt-contrib-connect
                    middlewares.push(function(req, res, next) {
                        req.setHeader('Access-Control-Allow-Origin', '*');
                        req.setHeader('Access-Control-Allow-Methods', '*');
                        return next();
                    });

                    return middlewares;
                }
            }
        }
}

将keepalive与中间件一起使用有问题吗?

4

1 回答 1

17

很遗憾,之前没有人对此做出回应。

您的代码看起来就像在文档中一样,但是您将标题添加到req而不是res.

第二个问题是文档误导您进入(已修复)使用.push. 您的代码根本没有被调用,因为它之前的某些东西正在执行 ares.end和/或不调用next().

您的固定代码如下所示:

    middleware: function (connect, options, middlewares) {
                    // inject a custom middleware 
                    middlewares.unshift(function (req, res, next) {
                        res.setHeader('Access-Control-Allow-Origin', '*');
                        res.setHeader('Access-Control-Allow-Methods', '*');
                        //a console.log('foo') here is helpful to see if it runs
                        return next();
                    });

                    return middlewares;
                }
于 2014-07-01T10:55:14.357 回答