【发布时间】:2019-12-30 16:01:17
【问题描述】:
我想用我的 Angular 客户端向我的 spring-boot 服务器发送一个 POST 请求。
服务器成功接收到数据和anwser,代码为200,正文包含“ok”。
但是客户端收到 null 作为 anwser。
角度代码:
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Methods': 'POST, GET'
})
};
this.http.post(this.URL, JSON.stringify(this.alert), this.httpOptions)
.subscribe((result: string) => {
if (result == null || result === 'error') {
//if fail;
} else {
//if success;
}
console.log('result :' + result);
})
春季启动代码:
@CrossOrigin(origins = "http://localhost:9000")
@PostMapping(value = "/url")
public ResponseEntity objDataController(@RequestBody ObjData objData) {
HttpHeaders resHeader = new HttpHeaders();
resHeader.set("origin", "http://localhost:8080");
resHeader.set("Content-Type", "application/json");
resHeader.set("Accept", "application/json");
//some code
return ResponseEntity.ok()
.headers(resHeader)
.body("ok");
}
在 console.log 获取:
result :null
谢谢
【问题讨论】:
-
您能否发送实际请求的屏幕截图(浏览器控制台的网络选项卡)。一切都在本地主机上运行吗?这可能是由于预检请求失败导致的一些 cors 问题。
-
你看过 f12 控制台的响应了吗?
-
@marcel 是的,服务器和客户端都在本地主机中,这就是我在 spring-boot 上使用
@CrossOrigin的原因 -
@JensAlenius 是的,回复说
result :null -
在 Angular 中,订阅方法回调首先是成功然后是错误。所以 HttpClient 将其视为成功。例如: .subscribe(successCallback,failureCallback) 并调用成功,正如我们在您的控制台中看到的那样。我认为身体可能是空的。你检查过 f12 中的 responsebody 吗?
标签: java angular spring-boot http angular-httpclient