grunt-connect-proxy解決開發時跨域問題


最近的項目中前后端是完全分離開發的,前端用grunt管理項目。這樣就會導致一個問題:開發時前端調用后台的接口時因為不在一個服務器,所以會出現跨域問題。但是也不能用JSONP或CROS方式實現真正的跨域,因為項目發布時其實是在同一個服務器下的。

這時候我們的grunt-connect-proxy就出場了,它就是專門解決這個問題的。

具體配置:

1. 先下載安裝這個組件

npm install grunt-connect-proxy --save-dev

這里要注意:一定要提前先裝上grunt-contrib-livereload這個組件,不然grunt serve時會總是報錯

2.增加配置

var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
    return connect.static(require('path').resolve(dir));
};
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

這斷代碼要加在gruntfile.js頂部,module.exports上邊。

然后,再connect中添加proxy配置及livereload配置

connect: {
      options: {
        port: 9000,
        open: true,
        livereload: 35729,
        // Change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      proxies: [
                {
                    context: '/website',
                    host: 'www.somesite.com',
                    port: 80,
                    https: false,
                    changeOrigin: true
                }
            ],
      livereload: {
        options: {
          middleware: function (connect) {
                        return [
                            lrSnippet,
                            mountFolder(connect, '.tmp'),
                            connect().use('/bower_components', connect.static('./bower_components')),
                            mountFolder(connect, config.app),
                            proxySnippet,
                        ];
                    }
        }
      },
/***/
}

接下來,再serve這個task里添加proxy

grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'configureProxies',     //增加到livereload前邊
      'connect:livereload',
      'watch'
    ]);

 

OK,到這里代理就加上了!

參考:

https://github.com/drewzboto/grunt-connect-proxy

http://fettblog.eu/blog/2013/09/20/using-grunt-connect-proxy/

http://www.himysql.com/2014/07/29/grunt-connect-proxy-configure/

http://www.ngnice.com/posts/76c4bd0f7a4cdc


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM