向服务器发送 POST 请求,服务器响应为空,Angular - Spring-boot
Send POST request to server, Server's response is null, Angular - Spring-boot
我想用我的 angular 客户端向我的 spring-boot 服务器发送一个 POST 请求。
服务器成功接收到数据和带有 200 代码的 anwser 以及包含 "ok".
的字符串的正文
但是客户端收到 null 作为 anwser。
Angular代码:
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);
})
Spring-启动代码:
@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
谢谢
遇到了类似的问题,它有助于指定响应类型:
const headers = new HttpHeaders({'Content-Type': 'application/json'});
this.httpClient.delete(url, {headers: headers, responseType: 'text'});
这是 chrome 控制台在搞乱你,当涉及到 observables 时,它无法正确解释值。我想如果你在 'If success' 块中使用结果,它一定会起作用
好的,我解决了我的问题,我改变这个:
return ResponseEntity.ok()
.headers(resHeader)
.body("ok");
作者:
Gson gson = new Gson();
return ResponseEntity.ok()
.headers(resHeader)
.body(gson.toJson("ok", String.class));
感谢您的回答!
我想用我的 angular 客户端向我的 spring-boot 服务器发送一个 POST 请求。
服务器成功接收到数据和带有 200 代码的 anwser 以及包含 "ok".
的字符串的正文但是客户端收到 null 作为 anwser。
Angular代码:
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);
})
Spring-启动代码:
@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
谢谢
遇到了类似的问题,它有助于指定响应类型:
const headers = new HttpHeaders({'Content-Type': 'application/json'});
this.httpClient.delete(url, {headers: headers, responseType: 'text'});
这是 chrome 控制台在搞乱你,当涉及到 observables 时,它无法正确解释值。我想如果你在 'If success' 块中使用结果,它一定会起作用
好的,我解决了我的问题,我改变这个:
return ResponseEntity.ok()
.headers(resHeader)
.body("ok");
作者:
Gson gson = new Gson();
return ResponseEntity.ok()
.headers(resHeader)
.body(gson.toJson("ok", String.class));
感谢您的回答!