Stephen Cole
Stephen Cole

Reputation: 13

POST https://accounts.spotify.com/api/token 415 Unsupported Media when using fetch

I'm trying to make a request to get an authorization code from the spotify api using fetch but I keep getting a 415 error code.

class CodeHandler {
  constructor(Args){
    this._args = Args;
    this.opts = {
       data: {
         name: "test",
         public: "false",
     grant_type: 'authorization_code',
     code: this._args[1],
     redirect_uri: 'http%3A%2F%2Ftest.openjukeboxdev.info%2F'
       },
       headers: {
         'Authorization': 'Basic ZjRmMTk0MTIzOTM3NDgyMmI5Mjg3OGY4YTUzYjUwMjk6MDVlODA3ZDk0NDljNGE1MmFlMzM1YTQxOTlhMjMzYmI'
       }}
  }

  response() {
    console.log(this.opts)
    console.log(JSON.stringify(this.opts))
    return this._args[1];
  }

  getAccessToken(){
    const url = "https://accounts.spotify.com/api/token";

    fetch(url, {
      method: 'post',
      body: JSON.stringify(this.opts)
    })
   .then(function (data) {
      console.log('Request succeeded with JSON response', data);
    })
    .catch(function (error) {
      console.log('Request failed', error);
    }); 
  }
  pausePlayback(){
    const http = new XMLHttpRequest();
    const url = 
    http.open("POST", url);
    http.send();
    alert(http.responseText);
  }
}

This is the full error. I get when I try to make the post request.

Response {type: "cors", url: "https://accounts.spotify.com/api/token", redirected: false, status: 415, ok: false, …}
type: "cors"
url: "https://accounts.spotify.com/api/token"
redirected: false
status: 415
ok: false
statusText: ""
headers: Headers
__proto__: Headers
body: (...)
bodyUsed: false
__proto__: Response

Upvotes: 1

Views: 540

Answers (3)

Stephen Cole
Stephen Cole

Reputation: 13

I added "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" and encoded my json body and it's all working now

Upvotes: 0

Ankit Vijay
Ankit Vijay

Reputation: 4108

415 - Unsupported Media is a client error which indicates that the server has refused to accept the request because the request payload is of an unsupported format.

The possible error could be due to the wrong Content-Type or Content-Encoding. Your request seem to be of JSON format. Try setting the Content-Type to application-json (if not already) and see if this resolves the issue.

Upvotes: 0

Evert
Evert

Reputation: 99543

415 suggests you are sending data with the incorrect Content-Type header.

Upvotes: 1

Related Questions