将POST请求发送到服务器,服务器的响应为null,Angular-Spring-boot

时间:2019-08-26 12:53:35

标签: java angular spring-boot http angular-httpclient

我想使用我的角度客户端将POST请求发送到我的spring-boot服务器。

服务器成功接收到数据并使用200 Code进行应答,并使用包含“ ok”的字符串的正文。

但是客户端收到的答案为空。

角度代码:

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

谢谢

3 个答案:

答案 0 :(得分:0)

遇到类似的问题,它有助于指定响应类型:

const headers = new HttpHeaders({'Content-Type': 'application/json'});
this.httpClient.delete(url, {headers: headers, responseType: 'text'});

答案 1 :(得分:0)

这是Chrome控制台让您感到困惑,当涉及可观察对象时,它无法正确解释该值。我想如果您在“如果成功”栏中使用结果,那么它一定会起作用

答案 2 :(得分:0)

好,我解决了我的问题,我对此进行了更改:

return ResponseEntity.ok()
                .headers(resHeader)
                .body("ok");

通过:

Gson gson = new Gson();
return ResponseEntity.ok()
                .headers(resHeader)
                .body(gson.toJson("ok", String.class));

谢谢你的帮助!

相关问题