【问题标题】:How to fix the 415 / Unsupported media type error?如何修复 415 / 不支持的媒体类型错误?
【发布时间】:2019-06-14 23:13:55
【问题描述】:

我正在使用 Angular 进行 POST。我已经在 Postman 中成功完成了它,所以我现在只是想在我的 Angular 应用程序中得到它。

当我尝试以角度发出请求时,我得到一个

Status Code: 415 / Unsupported Media Type

控制台里也有很长的错误码

ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{"_t":"Map","_i":{},"_s":0},"lazyUpdate":null},"status":415,"statusText":"Unsupported Media Type"

所以在 Postman 中,我能够成功地进行 POST。我使用 Postman 内置代码选项来正确获取所有标题,看起来像这样

"headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "User-Agent": "PostmanRuntime/7.13.0",
    "Accept": "*/*",
    "Cache-Control": "no-cache",
    "Postman-Token": "4eac9c16-3e20-44d0-be8d-414ead01bdc6,107a109d-62dd-4b52-b84d-e60d3ad092c4",
    "cookie": "JSESSIONID=F09A8E826390A6B788B9E45E0E663ECD.pc4bsfapi06t",
    "accept-encoding": "gzip, deflate",
    "content-length": "2337",
    "Connection": "keep-alive",
    "cache-control": "no-cache"

我使用了以下标题:

"Content-Type": "application/x-www-form-urlencoded",
    "Accept": "*/*",
    "Cache-Control": "no-cache",
    "accept-encoding": "gzip, deflate",
    "content-length": "2337",
    "Connection": "keep-alive",
    "cache-control": "no-cache"

我通过执行以下操作来设置它们:

let idpOptions ={
           headers: new HttpHeaders({
              "Content-Type": "application/x-www-form-urlencoded",
              "Accept": "*/*",
              "Cache-Control": "no-cache",
              "accept-encoding": "gzip, deflate",
              "content-length": "2337",
              "Connection": "keep-alive",
              "cache-control": "no-cache"
              }),
          withCredentials: true,
        };

然后做了:

 this.http.post(idpUrl, idpOptions)

我希望这个请求能够工作,因为它在邮递员中工作,并且我使用了我认为的所有必要的标头。

【问题讨论】:

  • 您是如何设置 HTTP 标头的?
  • @youri 我添加了一些关于我如何定义标题的代码
  • 您必须像这样调用您的 POST:this.http.post(idpUrl, null, idpOptions)。看看Angular example
  • @youri 谢谢!这修复了 415 错误。我现在遇到了一个不同的错误,但这肯定有助于我前进。再次感谢!
  • @youri 在文档中了解了 POST 请求。那么这里为什么要设置为null呢?

标签: angular http post


【解决方案1】:

HTTP post 调用不正确,您的第二个参数用于请求正文:https://angular.io/api/common/http/HttpClient#post

改变这个:

this.http.post(idpUrl, idpOptions)

对此(假设您不需要任何请求正文):

this.http.post(idpUrl, null, idpOptions)

您也可以查看Angular documentation

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 2018-07-25
    • 2016-09-09
    • 2017-08-28
    • 1970-01-01
    • 2021-10-12
    • 2017-10-23
    • 2014-10-02
    • 2014-06-21
    相关资源
    最近更新 更多