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

最近的項目中先後端是徹底分離開發的,前端用grunt管理項目。這樣就會致使一個問題:開發時前端調用後臺的接口時由於不在一個服務器,因此會出現跨域問題。可是也不能用JSONP或CROS方式實現真正的跨域,由於項目發佈時實際上是在同一個服務器下的。前端

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

具體配置:git

1. 先下載安裝這個組件github

npm install grunt-connect-proxy --save-devweb

這裏要注意:必定要提早先裝上grunt-contrib-livereload這個組件,否則grunt serve時會老是報錯sql

2.增長配置npm

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

相關文章
相關標籤/搜索