【问题标题】:Error when making POST request to server from angular 5从角度 5 向服务器发出 POST 请求时出错
【发布时间】:2018-03-22 15:33:47
【问题描述】:

当我向服务器发出 POST 请求时,它会返回此错误:

错误 Object { headers: {...}, status: 400, statusText: "OK", url: "serverURL", ok: false, name: "HttpErrorResponse", message: "Http failure response for serverURL: 400 OK", error: null }

我成功地向同一个 URL 发出了 DELETE 请求,并且我可以使用我的浏览器访问数据。 POST 请求如下所示:

    private postrequest() {
            const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type':  'application/json',
            })
        };
            let body = {
       firstname:this.myarray[0],
       host:(this.myarray[1]+':'+this.myarray[2])
       }

       return this.http.post(this.serverURL, body, httpOptions ).subscribe(res => console.log(res));
   }

成功的 DELETE 请求如下所示:

private deleterequest() {
        for (var i = this.delArray.length - 1; i >= 0; i--) {
            if ((this.delArray[i]) !== undefined) {
                const httpOptions = {
                headers: new HttpHeaders({
                    'Content-Type':  'application/json',
                })
            };
                this.http.delete(this.serverURL  + this.delArray[i], httpOptions).subscribe(res => console.log(res));

            }
        }
        this.getPeers();
    }

【问题讨论】:

  • 为什么要在 DELETE 请求中添加 Content-Type 标头?
  • HTTP 400 只是意味着服务器说这是一个错误的请求。它没有说明请求有什么不好。你需要做更多的调试。
  • (服务器看起来很糟糕,因为它说的是400 OK而不是400 Bad Request200 OK。)
  • 您正在创建标头但不发送它们
  • options 变量在两个代码示例中均未使用。

标签: html angular rest post


【解决方案1】:

您忘记添加选项

private postrequest() {
    let headers = new Headers({ 'Content-Type': 'application/json','Accept': 'q=0.8;application/json;q=0.9'});
    let options = new RequestOptions({headers: headers});
    let search = new URLSearchParams();
    this.http.post(this.serverURL, {firstname:this.myarray[0], host:(this.myarray[1]+':'+this.myarray[2])}, options).subscribe(res => console.log(res));
}

【讨论】:

  • 不幸的是不起作用。我已经整理好了,我将编辑问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
相关资源
最近更新 更多