具有keepalive true的grunt-contrib-connect中间件CORS解决方案

abs*_*olz 14 cors grunt-contrib-connect

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

我使用的是grunt-contrib-connect的0.7.1版本.

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;
                }
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

使用keepalive和中间件有问题吗?

nau*_*tur 17

很遗憾没有人回应过这个问题.

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

第二个问题是 文档误导你进入(修复)添加你的中间件.push.您的代码根本不会被调用,因为它之前正在执行res.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;
                }
Run Code Online (Sandbox Code Playgroud)