AngularJS withCredentials

前端之家收集整理的这篇文章主要介绍了AngularJS withCredentials前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在一个AngularJS项目,必须发送AJAX调用到restfull webservice。这个webservice是在另一个域上,所以我不得不在服务器上启用cors。我通过设置这些标题
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin","http://localhost:8000");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials","true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods","GET,POST,DELETE,PUT");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers","Content-Type,Accept,X-Requested-With");

我可以发送AJAX请求从AngularJS到后端,但我面临一个问题,当我尝试获取一个会话的属性。我相信这是因为sessionid cookie没有发送到后端。

我能够解决这个在jQuery中通过设置withCredentials为true。

$("#login").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/login",data : '{"identifier" : "admin","password" : "admin"}',contentType : 'application/json',type : 'POST',xhrFields: {
            withCredentials: true
        },success: function(data) {
            console.log(data);
        },error: function(data) {
            console.log(data);
        }
    })
});

$("#check").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/ping",method: "GET",success: function(data) {
            console.log(data);
        }
    })
});

我面临的问题是,我不能让这个工作在AngularJS与$ http服务。我试着这样:

$http.post("http://localhost:8080/api/login",$scope.credentials,{withCredentials : true}).
            success(function(data) {
                $location.path('/');
                console.log(data);
            }).
            error(function(data,error) {
                console.log(error);
            });

任何人都可以告诉我我做错了什么?

你应该传递一个配置对象,像这样
$http.post(url,{withCredentials: true,...})

或在旧版本:

$http({withCredentials: true,...}).post(...)

参见your other question

原文链接:https://www.f2er.com/angularjs/145739.html

猜你在找的Angularjs相关文章