我正在发布一个请求,我想收到一个“成功”字符串作为响应。我收到一个HttpResponseError,下面的图像中发布了以下信息。
PurchaseOrderService
postPurchaseOrderCustom(purchaseOrderCustom: PurchaseOrderSaveCustom) {
const url = `${this.localUrl}purchaseOrderCustom`;
return this.http.post<String>(url, purchaseOrderCustom, {headers: this.header})
.pipe(
catchError(this.handleError('postPurchaseOrderCustom', 'I am an error'))
);
}
PurchaseOrderComponent
this.purchaseOrderService.postPurchaseOrderCustom(purchaseOrderCustom).subscribe( response => {
console.log("Testing", response);
},
error => {
console.error('errorMsg',error );
}
我的操作方式与文档中的操作方式相同。一定要向我指出我在做错什么。
答案 0 :(得分:7)
这与您的api响应类型有关,success
是无效的json格式,默认情况下,HttpClient
是json响应类型,请稍后再尝试解析。您可以通过将响应类型设置为 text 这样
return this.http.post<String>(url, purchaseOrderCustom,
{headers: this.header , responseType:'text'})
.pipe (catchError(this.handleError('postPurchaseOrderCustom', 'I am an error')));
答案 1 :(得分:2)
就像已经说过的那样,这与服务器发出的响应有关。
就我而言,我有一个Spring Boot应用程序返回了以下内容:
return new ResponseEntity<>("Your SSN was generated successfully", HttpStatus.OK);
这是我在Angular端得到的响应:
{error: SyntaxError: Unexpected token Y in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHtt…, text: "Your SSN was registered successfully."}
所以我要做的是在Spring Boot应用程序中创建一个自定义CustomHttpResponse
类,然后将控制器中的代码更改为此:
...
CustomHttpResponse customHttpResponse = new CustomHttpResponse();
customHttpResponse.setMessage("Your SSN was registered successfully.");
customHttpResponse.setStatus(HttpStatus.OK.value());
return new ResponseEntity<>(new Gson().toJson(customHttpResponse),
HttpStatus.OK);
}
现在我得到了:
{message: "Your SSN was registered successfully.", status: 200}
message: "Your SSN was registered successfully."
status: 200
本质上,当Angular需要JSON但获取其他内容时,会发生此错误
答案 2 :(得分:0)
在获取pdf数据缓冲区作为响应时,我也面临着同样的问题,并且我按照以下方式进行了处理,它对我有用
服务器端
pdf.create(output, options).toBuffer((err: any, buffer: any) => {
if (err) reject(err);
response.type('pdf');
response.send(buffer);
});
在Angular服务中 downloadPdf(dateRange,labs){
return this.httpClient.post(url, data,{responseType:'blob'});
} 然后在Component.ts文件中
downPdf1(){
this.analyticService.downloadPdf(this.dateRange, this.labs).subscribe(
res => this.extractPdf(res),
(error:any) => throwError (error || 'Server error')
);
}
extractPdf(res){
let myBlob: Blob = new Blob([res], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(myBlob);
window.open(fileURL);
}