问题描述
我正在尝试使用Angular发出请求,并且我知道HTTP响应将不是JSON ,而是文本.但是,由于以下错误,Angular似乎期望得到JSON响应:
I'm trying to make a request in Angular and I know that the HTTP response will not be in JSON but in text. However, Angular seems to be expecting a JSON response since the error is the following:
以及
这是发布方法:
return this.http.post(this.loginUrl, this.createLoginFormData(username, password), this.httpOptions)
.pipe(
tap( // Log the result or error
data => console.log(data);
error => console.log(error)
)
);
和标题.
private httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/html, application/xhtml+xml, */*',
'Content-Type': 'application/x-www-form-urlencoded',
responseType: 'text'
},
) };
我认为responseType: 'text'
足以使Angular期待非JSON响应.
I thought that responseType: 'text'
would be enough to make Angular expect a non JSON response.
推荐答案
您已将responseType: 'text'
放在httpOptions
的错误部分中-它应位于headers
的外部中,像这样:
You've put responseType: 'text'
in the wrong section of your httpOptions
- It should sit outside of headers
, like so:
private httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/html, application/xhtml+xml, */*',
'Content-Type': 'application/x-www-form-urlencoded'
}),
responseType: 'text'
};
使用以前的方法,将responseType
的请求标头发送到服务器,而不是简单地向Angular发出指令以将响应实际视为文本.
With what you had before, a request header of responseType
was being sent to the server, rather than simply having an instruction to Angular to actually treat the response as text.
这篇关于HTTPClient POST尝试解析非JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!