简体   繁体   中英

How to fix the 415 / Unsupported media type error?

I am using angular to make a POST. I have successfully done it in Postman, so I am now just trying to get it in my angular app.

When I am trying to make the request in angular I get a

Status Code: 415 / Unsupported Media Type

There is also a long error code in the console

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

So in Postman I am able to successfully make the POST. I used the Postman built-in code option in order to get all of the headers correct, which looks something like this

"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"

I used the following headers:

"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"

I set them by doing the following:

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,
        };

And then did:

 this.http.post(idpUrl, idpOptions)

I would expect this request to work since it is working in postman and I used, what I thought to be, all the necessary headers.

The HTTP post call is not correct, you second parameter is for the request body: https://angular.io/api/common/http/HttpClient#post .

Change this:

this.http.post(idpUrl, idpOptions)

To this (assuming you don't need any request body):

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

You can also have a look to the Angular documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM