• home > tools > Bundler > grunt >

    grunt前后台一体化调试!解决跨域问题!

    Author:[email protected] Date:

    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": {
    
      }
    }



    转载本站文章《grunt前后台一体化调试!解决跨域问题!》,
    请注明出处:https://www.zhoulujun.cn/html/tools/Bundler/grunt/2016_0317_7715.html

    上一篇:第一页
    延伸阅读: