grunt-contrib-connect中间件CORS解决方案与keepalive true [英] grunt-contrib-connect middleware CORS solution with keepalive true

查看:127
本文介绍了grunt-contrib-connect中间件CORS解决方案与keepalive true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For my local development system I am trying to serve front-end assets using grunt-contrib-connect. I need a cross-domain solution for using fonts in Firefox. The server runs just fine, but I cannot seem to get the headers set.

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

I am using version 0.7.1 of 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与中间件的问题?

Is there a problem using keepalive with middleware?

推荐答案

很遗憾,没有人早些时候回应。

It's sad that nobody responded to that earlier.

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

Your code looks just like in the documentation, but you add the headers to req instead of res.

第二个问题是文档误导你进入 (固定)使用 .push 添加您的中间件。你的代码根本不会被调用,因为在它之前的事情是做一个 res.end 和/或不调用 next()

The second problem is that the docs mislead you into(fixed) adding your middleware with .push. Your code is not called at all, because something before it is doing a res.end and/or not calling next().

您的固定代码如下所示:

Your fixed code would look like this:

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

这篇关于grunt-contrib-connect中间件CORS解决方案与keepalive true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆