同样的代码在Angular 2上工作,但在Angular 6上它在http上返回错误(即http失败到错误处理程序(,但请求成功(代码:200并按预期返回数据(
问题的更新摘要它基本上是cors问题
1-我使用的是Angular2 HTTP,而不是自Angular4 以来应用的HttpClient
2-虽然这不是主要问题,但我在chrome上显示了CORS错误(可能是在使用httpclient之后(
3-没有必要添加responsType,在解决了服务器端的cors错误后,它就工作了。
旧的错误代码:
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
let postParams = "grant_type=password&username="+username+"&password="+password;
this.http.post("api/Token", postParams, options)
.subscribe(data => {
console.log(data);
},
error => {
//can I get the response body here?
console.log(JSON.stringify(error));
此链接上存在相关问题https://github.com/angular/angular/issues/19555所以我尝试添加responseType,如下
此外,根据这个问题,我试图传递responseType属性,但它也不起作用Angular 6:如何在进行http调用时将响应类型设置为文本
this.http.post(AppSettings.apiaddress + "Token", postParams, {headers,responseType: ResponseContentType.Text})
如果现在还不能让它工作,有没有办法在错误处理程序上获取数据作为解决方法?
感谢您的帮助,但如果您不知道答案,无需否决,这样其他人可以提供帮助,谢谢
请尝试这种方式。
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let postParams = "grant_type=password&username="+username+"&password="+password;
this.http.post("api/Token", postParams, {headers, 'responseType': 'json'})
.subscribe(data => {
console.log(data);
},
error => {
//can I get the response body here?
console.log(JSON.stringify(error));
并尝试用var headers = new Headers();
到var headers = new HttpHeaders();
替代