2017-04-23 54 views
0

我有Angularjs应用程序连接到服务器使用API​​,我使用令牌认证,当我使用邮递员获取令牌时,它的作品完美,但是当我使用Angulajs与相同的标题和参数我得到错误:400。Angularjs访问控制允许来源

当我使用Fiddler检查了两个请求时,发现Angularjs的请求缺少Access-Control-Allow-Origin: *标题。

如何解决这个问题?

这里是用于获取令牌服务:为API服务器

AuthenticationApi.Login = function (loginData) { 
    //POST's Object 
    var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password; 

    var deferred = $q.defer(); 

    //the data will be sent the data as string not JSON object. 
    $http.post('http://localhost:53194/Token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) 
     .then(function (response) { 
      console.log(response); 
      localStorageService.set('authorizationData', 
       { 
        token: response.access_token, 
        userName: loginData.userName 
       }); 

      Authentication.isAuth = true; 
      Authentication.userName = loginData.userName; 
      console.log(Authentication); 
     deferred.resolve(response); 

    }, 
    function (err, status) { 
     logout(); 
     deferred.reject(err); 
    }); 

    return deferred.promise; 

}; 

,我心中已经完成CORS:

public void Configuration(IAppBuilder app) 
{ 
    ConfigureOAuth(app); 
    HttpConfiguration config = new HttpConfiguration(); 
    WebApiConfig.Register(config); 
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 
    app.UseWebApi(config); 
} 
+0

使CORS是100%的服务器端的问题。你只是用角度标记了这个,但没有与你的服务器端语言或服务器类型有关 – charlietfl

回答

3

我发现这个问题,我固定它。 在API服务器,我有这样的代码:

var cors = new EnableCorsAttribute("*", "*", "*"); 
     cors.PreflightMaxAge = 60; 
     config.EnableCors(cors); 

问题是在PreflightMaxAge,我只是评论它...它的工作!

如果这个问题不解决,尝试使用IE或Firefox,不使用Chrome,因为它不是CORS启用