简体   繁体   English

AngularJS访问控制允许原点

[英]Angularjs Access-Control-Allow-Origin

I have Angularjs app connects to a server using API, and i'm using token authentication, when i use Postman to get the token, it works perfect, but when i'm use Angulajs with the same header and parameters i got error:400. 我有Angularjs应用程序使用API​​连接到服务器,并且我正在使用令牌身份验证,当我使用邮递员获取令牌时,它可以完美工作,但是当我使用具有相同标头和参数的Angulajs时出现错误:400 。

When i checked both requests using Fiddler, i found that the request from Angularjs is missing Access-Control-Allow-Origin: * header. 当我使用Fiddler检查两个请求时,我发现Angularjs的请求缺少Access-Control-Allow-Origin: *标头。

How to fix this? 如何解决这个问题?

Here is the service used to get the token: 这是用于获取令牌的服务:

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;

};

for the API server, i'v done CORS: 对于API服务器,我已经完成了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);
}

i found the problem and i fixed it. 我发现了问题,并已解决。 in the API server, i have this code: 在API服务器中,我有以下代码:

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

The problem is in the PreflightMaxAge, i just commented it...It worked!!! 问题出在PreflightMaxAge中,我只是发表了评论……行之有效!!!

if the problem not solved, try to use IE or FireFox, don't use Chrome because it is not CORS enabled 如果问题仍未解决,请尝试使用IE或FireFox,请勿使用Chrome,因为未启用CORS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM