【问题标题】:415 Unsupported Media Type angular2415 不支持的媒体类型 angular2
【发布时间】:2016-11-26 21:14:42
【问题描述】:

我正在为 JavaScript 尝试 angular2,我能够发出 Http.get 请求,但是当我尝试发出 Http.post 请求时,它会返回 415 Unsupported Media Type 错误。

代码本身非常简洁,所以我不确定是什么导致了这个错误。我该如何解决这个问题?

var headers = new Headers();
headers.append('Content-Type', 'application/json');

console.log(headers.get('Content-Type'))            

return this.http.post(this.endpoint_url, data="test.json", headers=headers).subscribe(
    function(response){console.log("Success Response" + response)},
    function(error){console.log("Error happened : " + error)});

【问题讨论】:

  • 415 几乎肯定是您的服务器返回的内容。

标签: angular


【解决方案1】:

您的代码只是尝试将字符串 test.json 发布为请求的正文,而不是 test.json 文件的内容。

还请注意,您在 this.http.post() 参数中使用了 = 符号。那就是将值分配给变量并返回它们。

实际上,您的代码与以下内容相同:

return this.http.post(this.endpoint_url, "test.json", headers).subscribe(...

并且“test.json”不是有效的 JSON 字符串(这似乎是您想要的,因为您正在设置标头)。

如果你想发送test.json的内容,你应该首先HTTP GET它,然后才将结果作为帖子的正文发送。

【讨论】:

    【解决方案2】:

    在进入之前尝试对你的 json 进行字符串化

     this._http.post(this.standardUrl,
                JSON.stringify({
                    ClientVersion: '1.0.0.0',
                    ClientLanguage: 'en'
                }),  { headers: headers } )
            .subscribe((response: Response) => {
                    data = response.json();
                });
    

    这至少会提供一个 json 对象..

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 2014-05-10
      • 2019-05-01
      • 2017-06-30
      • 2017-07-05
      • 2015-08-21
      • 2015-08-29
      相关资源
      最近更新 更多