有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java向服务器发送POST请求,服务器的响应为null,启动

我想用angular客户端向spring boot服务器发送POST请求

服务器成功地接收到数据和一个包含200个代码和一个包含“ok”字符串的正文的WSER

但客户端作为anwser接收null

角度代码:

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");
    }

在控制台。日志获取: result :null

谢谢


共 (3) 个答案

  1. # 1 楼答案

    这是chrome控制台让你困惑,当涉及到可观测值时,它无法正确解释值。我想如果你在“如果成功”模块中使用结果,它肯定会起作用

  2. # 2 楼答案

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

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

    好的,我解决了我的问题,我改变了这个:

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

    作者:

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

    谢谢你的支持