2017-03-14 86 views
0

对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。头还是什么?

我的代码

.factory('AuthenticationService', 
    ['Base64', '$http', '$cookieStore', '$rootScope', '$timeout', 
    function (Base64, $http, $cookieStore, $rootScope, $timeout) { 
     var service = {}; 

     service.Login = function (UserName, Password, callback) { 

      /* Dummy authentication for testing, uses $timeout to simulate api call 
      ---------------------------------------------- 
      $timeout(function() { 
       var response = { success: UserName === 'test' && Password === 'test' }; 
       if (!response.success) { 
        response.message = 'UserName or Password is incorrect'; 
       } 
       callback(response); 
      }, 1000); 

      */ 


      /* Use this for real authentication 
      ----------------------------------------------*/ 
      $http({ 
       method: 'POST', 
       url: 'http://216.0.1.209/AuthenticateUser', 
       data: { 
        UserName: 'UserName', 
        Password: 'Password' 
        }, 
       headers: { 
        'content-type: multipart/form-data; boundary=---011000010111000001101001' 
         } 
       }).then(function(response) { 
        console.log(response) 
      }); 

     }; 

     service.SetCredentials = function (UserName, Password) { 
      var authdata = Base64.encode(UserName + ':' + Password); 

      $rootScope.globals = { 
       currentUser: { 
        UserName: UserName, 
        authdata: authdata 
       } 
      }; 

      $http.defaults.headers.common['Authorization'] = 'Basic' + authdata; // jshint ignore:line 
      $cookieStore.put('globals', $rootScope.globals); 
     }; 

     service.ClearCredentials = function() { 
      $rootScope.globals = {}; 
      $cookieStore.remove('globals'); 
      $http.defaults.headers.common.Authorization = 'Basic'; 
     }; 

     return service; 
    }]) 

测试在Chrome,火狐和IE,给予同样的结果“否‘访问控制允许来源’标头出现在所请求的资源。” ..

温暖的regars ..感谢您的任何帮助或建议

回答

0

当您的javascript发送请求到不同的域时,浏览器将引发此错误。

要在开发过程中临时解决此问题,可以使用chrome extension来禁止浏览器警告。

对于生产环境,如果您的javascript与您的API服务器有不同的域名,您需要将您的JavaScript域名列入您的API服务器白名单。

在服务器上使用不同的语言有不同的方式允许这个,谷歌[language] CORS会给你一些例子。要允许的域名必须与错误消息中的URL匹配,包括协议http/https以及是否存在尾部斜线。

注意:不建议使用*,除非您的API旨在被公众用户请求。