Amy*_*Amy 18 typescript angular angular-httpclient
我正在尝试在Angular中发出请求,我知道HTTP响应不是JSON而是文本.但是,Angular似乎期待JSON响应,因为错误如下:
SyntaxError:XMLHttpRequest.c中JSON.parse()位置0的JSON中的意外标记<
以及
解析http:// localhost:9时出现 Http失败...
这是post方法:
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)
)
);
Run Code Online (Sandbox Code Playgroud)
和标题.
private httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/html, application/xhtml+xml, */*',
'Content-Type': 'application/x-www-form-urlencoded',
responseType: 'text'
},
) };
Run Code Online (Sandbox Code Playgroud)
我认为这responseType: 'text'足以让Angular期望非JSON响应.
Kir*_*kin 19
你已经把responseType: 'text'你的错误的部分httpOptions-它应该坐在外面的headers,就像这样:
private httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/html, application/xhtml+xml, */*',
'Content-Type': 'application/x-www-form-urlencoded'
}),
responseType: 'text'
};
Run Code Online (Sandbox Code Playgroud)
使用之前的内容,将一个请求标responseType头发送到服务器,而不是简单地向Angular发出指令以将响应实际视为文本.
Mar*_*ben 11
这段代码终于对我有用,可以xhr下载pdf文件(Angular 6 / Laravel 5.6)。下载PDF文件和文本文件的专业是'responseType': 'blob' as 'json'
showPdf(filename: String){
this.restService.downloadFile(
'protected/getpdf',
{'filename': filename}
)
}
//method from restService
public downloadFile(endpoint:String, postData:Object){
var restService = this
var HTTPOptions = {
headers: new HttpHeaders({
'Accept':'application/pdf'
}),
'responseType': 'blob' as 'json'
}
this.http.post(this.baseurl+endpoint,postData,HTTPOptions )
.subscribe(
res => {
console.log(res) //do something with the blob
},
error => {
console.error('download error:', error)
},
() => {
console.log('Completed file download.')
}
)
}
Run Code Online (Sandbox Code Playgroud)
我通过Kirk Larkins Answer(非常感谢!)和长角github问题线程https://github.com/angular/angular/issues/18586#issuecomment-323216764找到了解决方案
如果您只想接收纯文本。您可以设置没有标题的 Http 选项。
this.http.get("http://localhost:3000/login",{responseType: 'text'})
.subscribe((result)=>console.log(result))
Run Code Online (Sandbox Code Playgroud)
默认情况下,Angular 将响应类型设置为 JSON。
要覆盖它,您可以使用 headers 并将responseType设为'text'。
一个示例方法如下:
this.http.get(url, {responseType: 'text'})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13254 次 |
| 最近记录: |