Angular 2.0 Http post请求不发送凭据

时间:2016-01-11 06:31:20

标签: angular

当从高级客户端休息时调用Api时效果非常好,但是当我通过http来电时,它并没有按预期工作。这是因为它没有发送凭据。伙计们帮助我如何在withCredentials:true使用。

这是我的角度代码:

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/jiffy_fun/laravel/public/token',{headers: headers}).map(res => res.json()).subscribe(res => {this.token = res});

由于

3 个答案:

答案 0 :(得分:2)

我认为你混合了两件不同的东西。对于我在您提供的代码中看到的内容,您希望使用Angular2 HTTP类使用AJAX请求从表单发送凭据。在这种情况下,您需要在post方法的第二个参数中提供此内容,如下所述:

var creds = "username=" + username + "&password=" + password;

var headers = new Headers();
headers.append('Content-Type',
         'application/x-www-form-urlencoded');
this.http.post(
    'http://localhost/jiffy_fun/laravel/public/token',
    creds,
    {headers: headers})
.map(res => res.json())
.subscribe(res => {this.token = res});

withCredentials属性与CORS(跨域请求)有所不同。实际上,默认情况下,CORS不会为此类请求发送cookie。您可以通过在xhr对象上将withCredentials属性设置为true来选择更改此行为。此链接可以为您提供一些额外的提示:http://www.html5rocks.com/en/tutorials/cors/?redirect_from_locale=fr。请参阅此withCredentials部分。

希望它可以帮到你, 亨利

答案 1 :(得分:1)

有些事情让人想起 - 你正在进行POST但是将标题作为正文发送。

使用withCredentials可以与下面的标题一起设置。 对不起,现在没有时间去吸烟:S

let headers = {
  'Content-Type' : 'application/x-www-form-urlencoded'
}
let options = new RequestOptions({ headers: headers, withCredentials: true });

this.http.post('http://localhost/jiffy_fun/laravel/public/token',JSON.stringify({}),options).map(res => res.json()).subscribe(res => {this.token = res});

我不确定http API如何处理空的url编码体,因此选择了最安全的字符串化空对象选项 - 但确定这可以整理一下!

希望有所帮助!

答案 2 :(得分:0)

您在http post电话中缺少body参数。

// Http post function declaration
post(url: string, body: string, options?: RequestOptionsArgs) : Observable<Response>

https://angular.io/docs/ts/latest/api/http/Http-class.html

相关问题