首頁 > tools > grunt > > 正文

grunt前后臺一體化調試!解決跨域問題!

發布人:[email protected]    點擊:

grunt 如何跨域?如何端口轉發:端口轉發???一般,就是,設置什么瀏覽器?加什么 --disable-ser^^^^什么鬼的…… 這個,…………然后,你想到,nginx代理轉發??但是,你要手工刷新啊?? 哥哥!! 不想手工刷新!!!

grunt 如何跨域?如何端口轉發:端口轉發???

一般,就是,設置什么瀏覽器?加什么 --disable-ser^^^^什么鬼的……

這個,…………

blob.png

百度下:基本都是這個鳥樣子……

connect: {
  options: {
    port: 9000,
    // Change this to '0.0.0.0' to access the server from outside.
    hostname: 'localhost',
    livereload: 35729,

    // remove next from params
    middleware: function(connect, options) {
      return [
        function(req, res, next) {
          res.setHeader('Access-Control-Allow-Origin', '*');
          res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
          res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

          // don't just call next() return it
          return next();
        },

        // add other middlewares here 
        connect.static(require('path').resolve('.'))

      ];
    }
    },
    },

關鍵是?

這東西有毛用?

然后,你想到,nginx代理轉發??但是,你要手工刷新啊??

哥哥!!

不想手工刷新!!!

所以,值好,直接nodejs轉發!!

然后,我想寫這個文章的時候,自己配置完成后,然后谷歌……

居然,這位,已經寫了……

所以,只好拿來主義了!!簡略翻譯下哈!!

參考文章:

http://www.hierax.org/2014/01/grunt-proxy-setup-for-yeoman.html

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

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

插件地址:https://www.npmjs.com/package/grunt-connect-proxy




I'm working on a webapp using Angular.js with the help of the Yeoman workflow framework. Because the backend service runs on localhost:8080 and my dev server (through Grunt) on localhost:9000, requests result in same-origin policy errors due to the port difference. To get around this during development, we can setup CORS through a proxy on Grunt.

我angularjsjs庫搞webapp,采用yeoman管理工作流。服務端在8080端口,而前端grunt 卻跑在9000端口,由于瀏覽器的同源策略,所以會引起跨域問題。為了解決這個問題,我們通過 grunt-connect-proxy轉發。



Much of this post is adapted from the grunt-connect-proxy documentation for my project's Yeoman-created Grunt.js.

Tools used: 

  • yo (Yeoman) 1.0.7-pre.2

  • generator-angular 0.7.1

  • grunt-cli v0.1.11

  • grunt v0.4.2

  • grunt-connect-proxy 0.1.7


I started with a working Angular webapp with Yeoman and friends, so check out Yeoman and generator-angular to get up to speed.

  1. Install grunt-connect-proxy in the root of your project folder. The --save-dev parameter tells NPM to add grunt-connect-proxy as a devDependency to your project's package.json.


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

    NOTE: The grunt-connect-proxy documentation states that you can enable it by adding the following line to your Gruntfile.js:


    1
    grunt.loadNpmTasks('grunt-connect-proxy');


    When I added it, Grunt registered the task twice and while this didn't appear to cause any problems, this is the reason that I leave it out of my Gruntfile.js.

    Add a proxies config to your connect config. I added it just before livereload because we'll be modifying that config in the next step.

     proxies: [        {          context: '/api', // 這是你希望出現在grunt serve服務中的路徑,比如這里配置的是http://127.0.0.1:9000/api/          host: 'www.ngnice.com', // 這是你希望轉發到的遠端服務器          port: 80, // 遠端服務器端口          changeOrigin: true, // 建議配置為true,這樣它轉發時就會把host帶過去,比如www.ngnice.com,如果遠端服務器使用了虛擬主機的方式配置,該選項通常是必須的。          rewrite: {            '^/api/': '/remote_api/'  // 地址映射策略,從context開始算,把前后地址做正則替換,如果遠端路徑和context相同則不用配置。          }        }      ],

    11.jpg

    This rewrite rule tells the proxy that ever call which starts with user gets redirected to theuser context we defined earlier. It won't work the other way round, since the context has to be defined beforehand, but that shouldn't matter actually. Feel free to include as many proxies and rewrites. Using this structure everything should work fine.

    blob.png

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // The actual grunt server settings
    connect: {
      options: {
        // content removed for brevity
      },
      proxies: [{
        context: '/data-service-path', // the context of the data service
        host: 'localhost', // wherever the data service is running
        port: 8080 // the port that the data service is running on
      }],
      livereload: {
        // content removed for brevity
      },

    Check out the grunt-connect-proxy documentation for details on proxy configuration.


  2. Add the grunt-connect-proxy proxyRequest function to middleware in connect.livereload.options. This causes all requests to the Grunt server for the path of the configured context to be proxied; I'll provide some examples at the end of the post on how URLs are mapped by default. Here's what we end up with:

    blob.png

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    // The actual grunt server settings
    connect: {
      options: {
        // content removed for brevity
      },
      proxies: [{
        context: '/data-service-path', // the context of the data service
        host: 'localhost', // wherever the data service is running
        port: 8080 // the port that the data service is running on
      }],
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app="">'
          ],
          middleware: function (connect, options) {
            var middlewares = [];
               
            if (!Array.isArray(options.base)) {
              options.base = [options.base];
            }
               
            // Setup the proxy
            middlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest);
     
            // Serve static files
            options.base.forEach(function(base) {
              middlewares.push(connect.static(base));
            });
     
            return middlewares;
          }
        }
      },

    This is different from the example given in the grunt-connect-proxy documentation in that my version doesn't make anything browseable.

    這是我配置代碼:


  3. connect: {
      options: {
        port: 9019,
        // Change this to '0.0.0.0' to access the server from outside.
        //hostname: 'localhost',
        //hostname: '127.0.0.1',
        hostname: '192.168.1.254',
        livereload: 35719
      },
      proxies: [{
        context: '/jsse', // the context of the data service
        host: 'localhost', // wherever the data service is running
        port: 8080 // the port that the data service is running on
      }],
      livereload: {
        options: {
          open: true,
    
          middleware: function (connect) {
            var middlewares= [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app),
              require('grunt-connect-proxy/lib/utils').proxyRequest
            ];
            return middlewares;
          }
        }
      },
  4. Add the configureProxy task to the Grunt serve task. Here's what my serve task ends up as:


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    grunt.registerTask('serve', function (target) {
      if (target === 'dist') {
        return grunt.task.run(['build', 'connect:dist:keepalive']);
      }
     
      grunt.task.run([
        'clean:server',
        'bower-install',
        'concurrent:server',
        'autoprefixer',
        'configureProxies:server', // added just before connect
        'connect:livereload',
        'watch'
      ]);
    });

    blob.png

  5. Start up the Grunt server with


    1
    grunt serve

    and you should see


    1
    2
    Running "configureProxies:server" (configureProxies) task
    Proxy created for: /data-service-path to localhost:8080

    in the console.

That's all for installation and configuration.

Here are some example proxied URLs:

Grunt serverBackend server
http://127.0.0.1:9000/data-service-pathhttp://127.0.0.1:8080/data-service-path
http://127.0.0.1:9000/data-service-path/foo/1http://127.0.0.1:8080/data-service-path/foo/1


For an Angular resource whose endpoint is over the proxy then, the proxy context must be used in the resource URL, something like this:

?

1
2
3
4
angular.module('myServices', ['ngResource'])
.factory('Foo', ['$resource', function($resource) {
    return $resource('/data-service-path/foo/:id', {id: '@id'});
}]);

To use a different path on the Grunt and backend servers, use the rewrite config; for example:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// The actual grunt server settings
connect: {
  options: {
    // content removed for brevity
  },
  proxies: [{
    context: '/api', // the path your application uses
    host: 'localhost', // wherever the data service is running
    port: 8080, // the port that the data service is running on
    rewrite: {
        // the key '^/api' is a regex for the path to be rewritten
        // the value is the context of the data service
        '^/api': '/data-service-path'
    }
  }],
  livereload: {
    // content removed for brevity
  },
  test: {

Example URLs:

Grunt serverBackend server
http://127.0.0.1:9000/apihttp://127.0.0.1:8080/data-service-path
http://127.0.0.1:9000/api/foo/1http://127.0.0.1:8080/data-service-path/foo/1


Then our example resource code becomes:


1
2
3
4
angular.module('myServices', ['ngResource'])
.factory('Foo', ['$resource', function($resource) {
    return $resource('/api/foo/:id', {id: '@id'});
}]);



全部配置代碼:

// Generated on 2015-12-02 using generator-angular 0.12.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Automatically load required Grunt tasks
  require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates',
    cdnify: 'grunt-google-cdn'
  });

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,
    sass: {
      dist: {
        files: [{
          expand: true,
          cwd: '/styles',
          src: ['*.scss'],
          dest:  '/styles',
          ext: '.css'
        }]
      }
    },
    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: ''
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      css: {
        //files: '**/*.scss',
        files: ['/styles/{,*/}*.scss'],
        tasks: ['sass'],
        sourceComments: 'normal'
      },
      styles: {
        files: ['/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: ''
        },
        files: [
          '/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9019,
        // Change this to '0.0.0.0' to access the server from outside.
        //hostname: 'localhost',
        //hostname: '127.0.0.1',
        hostname: '192.168.1.254',
        livereload: 35719
      },
      proxies: [{
        context: '/jsse', // the context of the data service
        host: 'localhost', // wherever the data service is running
        port: 8080 // the port that the data service is running on
      }],
      livereload: {
        options: {
          open: true,

          middleware: function (connect) {
            var middlewares= [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app),
              require('grunt-connect-proxy/lib/utils').proxyRequest
            ];
            return middlewares;
          }
        }
      },
      test: {
        options: {
          port: 9047,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: ''
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '/{,*/}*',
            '!/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      server: {
        options: {
          map: true,
        },
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '/scripts/{,*/}*.js',
          '/styles/{,*/}*.css',
          '/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '/index.html',
      options: {
        dest: '',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['/{,*/}*.html'],
      css: ['/styles/{,*/}*.css'],
      js: ['/scripts/{,*/}*.js'],
      options: {
        assetsDirs: [
          '',
          '/images',
          '/styles'
        ],
        patterns: {
          js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
        }
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s  will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '/scripts/scripts.js': [
    //         '/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '/images',
          src: '{,*/}*.svg',
          dest: '/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true
        },
        files: [{
          expand: true,
          cwd: '',
          src: ['*.html'],
          dest: ''
        }]
      }
    },

    ngtemplates: {
      dist: {
        options: {
          module: 'clientApp',
          htmlmin: '',
          usemin: 'scripts/scripts.js'
        },
        cwd: '',
        src: 'views/{,*/}*.html',
        dest: '.tmp/templateCache.js'
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '',
          dest: '',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: 'bower_components/bootstrap/dist',
          src: 'fonts/*',
          dest: ''
        }]
      },
      styles: {
        expand: true,
        cwd: '/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'copy:styles'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-connect-proxy');
  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer:server',
      'configureProxies:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'ngtemplates',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
{
  "name": "client",
  "private": true,
  "devDependencies": {
    "grunt": "^0.4.5",
    "grunt-angular-templates": "^0.5.7",
    "grunt-autoprefixer": "^2.0.0",
    "grunt-concurrent": "^1.0.0",
    "grunt-connect-proxy": "^0.2.0",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-concat": "^0.5.0",
    "grunt-contrib-connect": "^0.9.0",
    "grunt-contrib-copy": "^0.7.0",
    "grunt-contrib-cssmin": "^0.12.0",
    "grunt-contrib-htmlmin": "^0.4.0",
    "grunt-contrib-imagemin": "^0.9.2",
    "grunt-contrib-jshint": "^0.11.0",
    "grunt-contrib-uglify": "^0.7.0",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-filerev": "^2.1.2",
    "grunt-google-cdn": "^0.4.3",
    "grunt-karma": "*",
    "grunt-newer": "^1.1.0",
    "grunt-ng-annotate": "^0.9.2",
    "grunt-svgmin": "^2.0.0",
    "grunt-usemin": "^3.0.0",
    "grunt-wiredep": "^2.0.0",
    "jit-grunt": "^0.9.1",
    "jshint-stylish": "^1.0.0",
    "karma-jasmine": "*",
    "karma-phantomjs-launcher": "*",
    "time-grunt": "^1.0.0"
  },
  "engines": {
    "node": ">=0.10.0"
  },
  "scripts": {
    "test": "grunt test"
  },
  "dependencies": {
    "grunt-contrib-sass": "^0.9.2"
  }
}
{
  "name": "client",
  "version": "0.0.0",
  "dependencies": {
    "angular": "^1.3.0",
    "angular-animate": "^1.3.0",
    "angular-cookies": "^1.3.0",
    "angular-messages": "^1.3.0",
    "angular-resource": "^1.3.0",
    "angular-route": "^1.3.0",
    "angular-sanitize": "^1.3.0",
    "angular-touch": "^1.3.0"
  },
  "devDependencies": {
    "angular-mocks": "^1.3.0"
  },
  "appPath": "app",
  "moduleName": "clientApp",
  "overrides": {

  }
}


上一篇:First page
延伸閱讀: