【问题标题】:Angular 2.0 Http post request does not send credentialsAngular 2.0 Http 发布请求不发送凭据
【发布时间】:2017-09-19 02:04:02
【问题描述】:

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});

谢谢

【问题讨论】:

  • this.http.post 的语法是否正确?我认为应该是$http 而不是http
  • @KhalidHussain this.http.post 在 angular2 中是正确的。 $http 来自角度 1。

标签: angular


【解决方案1】:

我认为你混合了两种不同的东西。对于我在您提供的代码中看到的内容,您希望使用 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 部分。

希望对你有帮助 蒂埃里

【讨论】:

  • 我在高级客户端休息中获得了所需的结果,但不是通过角度。实际上,在每个由 Angular 发出的请求中,它都会创建一个新的会话文件,但使用高级客户端它会简单地更新当前会话。请帮忙...
  • 您使用哪个 REST 客户端?您能否在问题中告诉我们您在此客户端中放置的内容(标头、有效负载、HTTP 方法)?谢谢!
  • 我在问题中提到的高级客户端休息
  • 好的,知道了!您能否将您的问题更新为来自 REST 高级客户端(标头、有效负载、HTTP 方法)的请求和响应的内容?谢谢!
【解决方案2】:

我想到了一些事情 - 您正在执行 POST,但将标头作为正文发送。

withCredentials 可以与下面的标题一起设置。 抱歉,现在没有时间去 plunkr :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 编码主体,因此选择了字符串化空对象的最安全选项 - 但肯定可以整理一下!

希望有所帮助!

【讨论】:

    【解决方案3】:

    您的 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

    【讨论】:

    • 我没有发送任何东西。我只想得到令牌
    • 嘿,兄弟,我将值 null 放在正文中,但它仍在创建 laravel 会话文件
    猜你喜欢
    • 2015-12-30
    • 2019-09-15
    • 2018-08-04
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2023-04-01
    • 2016-11-15
    • 2018-08-19
    相关资源
    最近更新 更多