2014-04-10 32 views
14

對於我的本地開發系統,我嘗試使用grunt-contrib-connect來服務前端資產。我需要一個在Firefox中使用字體的跨域解決方案。服務器運行得很好,但我似乎無法獲得標頭設置。grunt-contrib-connect中間件CORS解決方案,keepalive爲true

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

是否有使用存活與中間件的問題嗎?

回答

17

很遺憾沒有人對此做出迴應。

您的代碼看起來就像在文檔中,但您將標題添加到req而不是res

第二個問題是該文檔誤導您(fixed)添加您的中間件與.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; 
       } 
+0

謝謝!如果不是你的問題,我永遠不會想到這件事。 https://github.com/gruntjs/grunt-contrib-connect/issues/114 –

+0

這很混亂。我調試了它,不得不猜測發生了什麼:|很高興我幫了忙! – naugtur