如何允许跨域请求

时间:2015-07-21 19:09:07

标签: angularjs xmlhttprequest cors

我使用$ resource来进行http调用,我的后端应用程序部署在不同的端口上。当我尝试使用请求方法(GET)从服务器获取数据时,我的浏览器会自动附加请求方法(OPTIONS)。我阅读了有关浏览器行为的好文章,但无法找到问题。

我允许在服务器上使用Access-Control-Allow-Methods,但它不能正常工作

我不了解服务器请求,请告诉我那里出了什么问题,为什么会这样?

我的咕噜声配置

'use strict';

module.exports = function (grunt) {

    require('autostrip-json-comments');
    var fs = require('fs');
    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    var appSettings = require('./config/application.conf.json');

    grunt.initConfig({


        // Set the application settings
        settings: appSettings,


        connect: {
            options: {
                hostname: '<%= settings.dev.hostname %>',
                port: '<%= settings.dev.port %>',
                livereload: '<%= settings.dev.liveReloadPort %>',
                options: {
                    index: 'index.html',
                    maxAge: 300000
                }
            },
            livereload: {
                options: {
                    open: true,
                    base: [
            '.tmp',
            '<%= settings.dev.dir %>'
          ],
                    index: 'index.html'
                }
            },
            devel: {
                options: {
                    port: '<%= settings.dev.port %>',
                    hostname: '<%= settings.dev.hostname %>',
                    base: {
                        path: '<%= settings.dev.dir %>',
                        options: {
                            index: 'index.html'
                        }
                    },
                    middleware: function (connect, options, middlewares) {
                        middlewares.unshift(function (req, res, next) {
                            res.setHeader('Access-Control-Allow-Origin', '*');
                            res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                            return next();

                        });

                        return middlewares;
                    }
                }
            },
            dist: {
                options: {
                    port: '<%= settings.dist.port %>',
                    hostname: '<%= settings.dist.hostname %>',
                    base: {
                        path: '<%= settings.dist.dir %>',
                        options: {
                            index: 'index.html',
                            maxAge: 300000
                        }
                    },
                    middleware: function (connect, options, middlewares) {
                        middlewares.unshift(function (req, res, next) {
                            res.setHeader('Access-Control-Allow-Origin', '*');
                            res.setHeader('Access-Control-Allow-Methods', '*');
                            return next();

                        });

                        return middlewares;
                    }
                }
            },
        },
        watch: {
            json: {
                files: ['<%= settings.dev.dir %>/**/*.json', '!<%= settings.dev.dir %>/core/*.json'],
                tasks: ['ngconstant:development'
               ]
            }
        },
        // jsHint config
        jshint: {
            options: {
                jshintrc: __dirname + '/.jshintrc',
                reporter: require('jshint-stylish'),
                force: true
            },
            all: [
        // 'Gruntfile.js',
        '<%= settings.dev.dir %>/scripts/**/*.js'
      ],
        },
        uglify: {
            options: {
                mangle: false,
                compress: {
                    drop_console: true
                }
            }
        },
        less: {
             dist: {
                options: {
                    style: 'expanded',
                    compass: false
                },
                files: {
                    '<%= settings.dist.dir%>/assets/css/application.css': '<%= settings.dev.dir%>/assets/less/application.less'
                }
             },
             dev: {
                options: {
                    style: 'expanded',
                    compass: false,
                    sourceMap:'true',
                    sourceMapFilename: '<%= settings.dev.dir%>/assets/css/application.css.map',
                    sourceMapURL: '<%= settings.dev.dir%>/assets/css/application.css.map',
                    sourceMapBasepath: '<%= settings.dev.dir%>/assets/css/application.css.map'
                },
                files: {
                    '<%= settings.dev.dir%>/assets/css/application.css': '<%= settings.dev.dir%>/assets/less/application.less'
                }
             },
        },
        cssmin: {
            target: {
                files: [{
                    expand: true,
                    cwd: '<%= settings.dist.dir %>/assets/css',
                    src: ['*.css', '!bower_components/**'],
                    dest: '<%= settings.dist.dir %>/assets/css',
                    ext: '.min.css'
        }]
            }
        },
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
            '.tmp',
            '<%= settings.dist.dir %>/*',
            '!<%= settings.dist.dir %>/.git*'
          ]
        }]
            },
            server: '.tmp',
            docs: '<%= settings.docs.dir %>',
            coverage: '<%= settings.test.coverage.dir %>'
        },

        // Copy config
        copy: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= settings.dev.dir %>',
                    dest: '<%= settings.dist.dir %>',
                    src: ['**/**', '!assets/less/**']
        }]
            }
        },
        ngconstant: {
            // Options for all targets
            // Environment targets
            development: {
                options: {
                    dest: '<%= settings.dev.dir %>/core/config.constant.js',
                    space: '  ',
                    wrap: '\n\n {%= __ngModule %}',
                    name: 'Config',
                },
                constants: {
                    $enviornment: require('./config/development.json')
                }
            },
            production: {
                options: {
                    dest: '<%= settings.dev.dir %>/core/config.constant.js',
                    space: '  ',
                    wrap: '\n\n {%= __ngModule %}',
                    name: 'Config',
                },
                constants: {
                    $enviornment: require('./config/production.json')
                }
            },
        }

    });
    /* @discription
     n {string} it is build type can be production/development/staging*/
    grunt.registerTask('build', 'Build a production ready app', function (n) {
        if (n == null) {
            grunt.warn('Build type must be specified');
        }

        //remove console from script
        if (n == "production") {
            grunt.config('uglify.options.compress.drop_console', true);
        } else {
            grunt.config('uglify.options.compress.drop_console', false);
        }



        //grunt.config('copy.vendor.files[0].src', finalCopyFiles);


        grunt.task.run('clean:dist',
             'ngconstant:' + n,             
            'copy:dist',         
            'cssmin',
            'uglify',
            'less:dist'           
        );
    });

    grunt.registerTask('server', 'Start up the development live reload server', function (n) {
        console.log("server" + n);
        if (n == null) {
            grunt.warn('Build type must be specified');
        }
        grunt.task.run('ngconstant:' + n,
            'less:dev',           
            'connect:devel',
            'watch:json'
            // 'concurrent:dev'
        );
    });
    grunt.registerTask('default', 'Run all servers.', [
    'server'
  ]);

    grunt.event.on('watch', function (action, filepath, target) {
        //grunt.task.run('server');
    });


}; 

我的服务是

angular.module('samepinch.login').factory('LoginService', ['$resource','$enviornment', function ($resource,$enviornment) {
    var url = $enviornment.backendurl;
     return $resource(url+'authenticate',{},{
         query: {method:'GET', params:{itemId:''}, isArray:true},
         post: {method:'POST'},
         update: {method:'PUT', params: {itemId: '@entryId'}},
          remove: {method:'DELETE'}
     });
}]);

我的控制器

&#39;使用严格的&#39;;

angular.module('samepinch.login').controller('LoginController',['$scope','LoginService','$rootScope',function($scope,LoginService,$rootScope){

    $rootScope.isLoginPage        = true;
    $rootScope.isLightLoginPage   = false;
    $rootScope.isLockscreenPage   = false;
    $rootScope.isMainPage         = false;

    $scope.register = function(credentials){
        LoginService.query(credentials,function(success){

        },function(error){

        });
    }

}]);

1 个答案:

答案 0 :(得分:0)

实际上,浏览器使用http请求方法“选项”在您的执行请求之前发出预检请求。因此您必须向此请求发送200 OK并允许跨域标头,如

httpResponse.setHeader("Access-Control-Allow-Origin", "*");
    httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
    httpResponse.setHeader("Access-Control-Max-Age", "3600");
    httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type");
    if(httpRequest.getMethod().equals("OPTIONS")){
        httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }