【发布时间】:2019-04-02 21:17:34
【问题描述】:
同样的代码在 Angular 2 上运行,但在 Angular 6 上它在 http 上返回错误(即 http 对错误处理程序失败)但请求成功(代码:200 并按预期返回数据)
更新问题总结,基本上是cors问题
1- 我使用 Angular2 HTTP 而不是 HttpClient 自 Angular4 以来应用
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: How to set response type as text while making http call
this.http.post(AppSettings.apiaddress + "Token", postParams, {headers,responseType: ResponseContentType.Text})
如果无法让它工作,有没有办法获取错误处理程序上的数据作为解决方法?
感谢您的帮助,但如果您不知道答案,无需投票,以便其他人提供帮助,谢谢
【问题讨论】:
-
你说你得到一个错误。什么错误?
-
您还在使用来自 Angular 的 Http 或 HttpClient 吗?那些标题看起来不太好。
-
@Zlatko http 将响应作为错误响应处理,因此它对错误处理程序失败,尽管响应成功,但预期的数据正确返回
-
使用 Http 而不是 HttpClient
-
如果您不知道答案无需投票,以便其他人提供帮助,谢谢