我想从Angular客户端发出POST请求。我有这个Spring端点:
@RestController()
public class HomeController {
@PostMapping(value = "/payment/{unique_transaction_id}", consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<WpfResponse> handleWpfMessage(@PathVariable("unique_transaction_id") String unique_transaction_id,
@RequestBody WpfPaymentsDTO transaction, HttpServletRequest request) throws Exception {
/// ....
return ResponseEntity.ok("http://some_domain.com/example");
}
}
我使用以下打字稿代码:
save(main: MainForm, hash: string): void {
this.http.post('http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74', main, { headers }).subscribe();
}
但是当我发出POST请求时,我得到了:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74", ok: false, …}
"SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:13388:51)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2781:31)
at Object.onInvokeTask (http://localhost:4200/vendor.js:54479:33)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2780:60)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2553:47)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2856:34)
at invokeTask (http://localhost:4200/polyfills.js:4102:14)
at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:4139:21)"
我的状态为OK,但找不到为什么我收到此错误消息。你知道我该怎么解决吗?
答案 0 :(得分:0)
我没有任何线索,但是从您的代码看来,您返回的是JSON,但是返回值为字符串"http://some_domain.com/example"
,而不是JSON。
答案 1 :(得分:0)
您需要在标题中包含{responseType:'text'}。即
const headers = {
responseType: 'text'
}
this.http.post('http://localhost:8080/some_package/payment/ckjzqtyxh5pnavbjecujhuvzaa5q8n74', main, { headers }).subscribe();
最新答案,但将来可以帮助其他人。