【问题标题】:angular2-rc4 http.post not working for chrome and IEangular2-rc4 http.post 不适用于 chrome 和 IE
【发布时间】:2016-07-13 21:03:02
【问题描述】:

我已经编写了一个服务来在@angular2-rc1 中执行http post 操作。更新到 rc4 后,它停止在 chrome 中工作,即虽然它在 firefox 中工作。
当我尝试通过发布请求发送数据时,它在请求中的萤火虫(检查铬元素)中显示数据,但服务器正在获取空字符串。 下面是代码:

import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions, BaseRequestOptions} from "@angular/http";
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/operator/map'

@Injectable()
export class HttpService {
    constructor(private http: Http) {
    }

    login(url:string, data: string) {
        let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'});
        let options = new RequestOptions({headers: headers});
        return this.http.post(url, data, options);
    }

}

用于调用此登录方法的代码是:

this._httpService.login('rest/j_spring_security_check', 'j_username=user&j_password=pass').subscribe(
                data => this.authenticationSuccess(data),
                error => this.authenticationFailure(error)
            )

当我尝试通过 Firefox 登录时,服务器正在正确获取用户名和密码,而如果通过 chrome 或 ie 完成相同操作,服务器将获取空字符串。 请帮忙。

【问题讨论】:

标签: angular angular2-routing


【解决方案1】:

您可以尝试像这样在 RC4 中直接使用 FormData 对象:

login(url:string, data: string) {
  var body = new FormData();
  body.append('j_username', data.user);
  body.append('j_password', data.pass);

  return this.http.post(url, body);
}

或 URLSearchParams 类:

login(url:string, data: string) {
  var body = new URLSearchParams();
  body.set('j_username', data.user);
  body.set('j_password', data.pass);

  return this.http.post(url, body);
}

并以这种方式调用login 方法:

httpService.login('rest/j_spring_security_check', {
  user: 'user', pass: 'pass').subscribe(...);

【讨论】:

  • 我正在使用 Spring Security 进行身份验证,它要求以这种格式传递请求数据:j_username=user&j_password=pass in a single line。如果我发送json格式的数据,spring security将无法读取。
猜你喜欢
  • 2015-06-21
  • 2016-08-09
  • 2012-01-27
  • 2012-02-14
  • 2013-07-09
  • 2015-05-07
  • 1970-01-01
  • 2013-04-22
  • 2016-01-29
相关资源
最近更新 更多