【问题标题】:Send POST request to server, Server's response is null, Angular - Spring-boot向服务器发送 POST 请求,服务器的响应为空,Angular - Spring-boot
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢,但我想这对我没有帮助,我使用 POST 而不是 DELETE,我的问题是 .subscribe
  • 可能仍然值得一试。 “我的问题在于订阅”是什么意思?因为如果您的 httpClient 尝试将“OK”字符串解释为 JSON,它将不会返回该字符串...
【解决方案2】:

这是 chrome 控制台在惹你生气,当涉及到 observables 时,它无法正确解释该值。我猜如果您在“如果成功”块中使用结果,它一定会起作用

【讨论】:

    【解决方案3】:

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

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

    作者:

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

    感谢您的回答!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2012-12-12
      • 2020-02-16
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      相关资源
      最近更新 更多