我有一个弹簧靴admin server
和一个angular-client
前部。我正在尝试使用HTTPClient从我的前端向我的服务器发送一些数据,但不知怎的,我在请求期间遇到以下错误,但首先是我的代码:
angular-client
中的POST请求:
runBatch(id: number, stateUpd: string): Observable<HttpEvent<{}>> {
const req = new HttpRequest('POST', '/update_state', {id, stateUpd}, {
reportProgress: true,
responseType: 'text'
});
return this.http.request(req);
}
angular-client
中的控制器:
changeBatchState(state: string): void {
if(this.selection.selected.length >= 1){
this.selection.selected.forEach(batchInstance =>{
if(batchInstance.batchState == 'CRASHED' || 'KILLED' || 'SUBMITTED'){
console.log(batchInstance.id + " setting to RUNNABLE...");
this.dataTableService.runBatch(batchInstance.id, state).subscribe(event => {
if(event.type === HttpEventType.UploadProgress) {
console.log('POST /update_state sending...');
}
else if(event instanceof HttpResponse) {
console.log('Request completed !');
}
});
}
else {
console.log(batchInstance.id + ' can not set to RUNNABLE');
}
});
}
}
admin server
中的控制器:
@PostMapping("/update_state")
public ResponseEntity<String> batchChangeState(@RequestParam("id") int id, @RequestParam("stateUpd") String stateUpd) {
try {
log.i("INSIDE CONTROLLER");
log.i("BATCH INSTANCE ID : " + id);
log.i("UPDATE REQUESTED : " + stateUpd);
return ResponseEntity.status(HttpStatus.OK).body("Batch instance: " + id + " updated");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body("Fail to update batch instance " + id);
}
}
这里是我在请求中得到的错误:
ERROR
Object { headers: {…}, status: 400, statusText: "OK", url: "http://localhost:8870/update_state", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:8870/update_state: 400 OK", error: "{\"timestamp\":1517473012190,\"status\":400,\"error\":\"Bad Request\",\"exception\":\"org.springframework.web.bind.MissingServletRequestParameterException\",\"message\":\"Required int parameter 'id' is not present\",\"path\":\"/update_state\"}" }
我不明白它来自哪里,因为我在POST请求中正确发送了id,有什么想法吗?
答案 0 :(得分:1)
const req = new HttpRequest('POST', '/update_state', {id, stateUpd}, {
将创建一个请求,其中{id,stateUpd}位于正文中,而不是在queryParams中。
你应该做
// change : Body = null, and data are in options.params
runBatch(id: number, stateUpd: string): Observable<HttpEvent<{}>> {
const req = new HttpRequest('POST', '/update_state', null, {
reportProgress: true,
responseType: 'text',
params: new HttpParams().set('id', id.toString()).set('stateUpd', stateUpd);
});
return this.http.request(req);
}