grunt-contrib-connect middleware CORS solution with keepalive true

↘锁芯ラ 提交于 2019-12-21 03:33:19

问题


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.

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

Is there a problem using keepalive with middleware?


回答1:


It's sad that nobody responded to that earlier.

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

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


来源:https://stackoverflow.com/questions/22992931/grunt-contrib-connect-middleware-cors-solution-with-keepalive-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!