使用keepalive为true的grunt-contrib-connect中间件CORS解决方案

14

我正在尝试使用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;
                }
            }
        }
}

在使用中间件时使用keepalive会有问题吗?

1个回答

17

很遗憾之前没有人回复。

你的代码看起来和文档中一样,但是你将头信息添加到了req而不是res

第二个问题是,文档误导你使用.push来添加你的中间件。(fixed)由于之前的某些操作使用了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;
                }

谢谢!如果不是因为你的问题,我永远也想不到这个。https://github.com/gruntjs/grunt-contrib-connect/issues/114 - Daniel Darabos
很令人困惑。我进行了调试,不得不猜测发生了什么 :| 很高兴能帮忙! - naugtur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接