0

I'm attempting to send a fetch POST request to a few 3rd party APIs. When testing this call in Postman I'm able to get a successful 200 response. Using the same code from Postman in my project returns a 415 Unsupported Media Type. I've been searching for a solution and I've tried sending it with the following headers as suggested by several posts and articles.

myHeaders.append("Content-Type", "application/json");
myHeaders.append("Access-Control-Allow-Origin", "*");
myHeaders.append("Accept", "application/json");

I've attached my API call down below and would be super helpful if anyone is able to spot why I'm getting this 415.

var myHeaders = new Headers();
myHeaders.append("xxxxx_api_key", "");
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Access-Control-Allow-Origin", "*");
myHeaders.append("Accept", "application/json");

var raw = JSON.stringify({
    api_key: "xxxxx_api_key",
    profiles: [{
      email: "thomas.jefferson@example.com",
      phone_number: "17326138213",
      example_property: "valueB",
    }],
  });
console.log(raw);
var requestOptions = {
  method: "POST",
  mode: "no-cors",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};

fetch("https://a.klaviyo.com/api/v2/list/XXXXX/members", requestOptions)
  .then((response) => response.json())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

This is the working request exported from Postman

curl --location --request POST 'a.klaviyo.com/api/v2/list/XXXXX/members' \ 
   --header 'Content-Type: application/json' \ 
   --header 'xxx_api_key;' \ 
   --data-raw '{ "api_key": "xxx_api_key", "profiles": [ { "email": "thomas.jefferson@example.com", "phone_number": "17326138213", "example_property": "valueB" } ] }'
derpirscher
  • 14,418
  • 3
  • 18
  • 35
Khalid
  • 259
  • 1
  • 2
  • 7
  • Please show how the working postman request looks like, when you export it (for instance as cURL) – derpirscher Apr 22 '21 at 13:18
  • curl --location --request POST 'https://a.klaviyo.com/api/v2/list/X3jKqa/members' \ --header 'Content-Type: application/json' \ --header 'xxx_api_key;' \ --data-raw '{ "api_key": 'xxx_api_key', "profiles": [ { "email": "thomas.jefferson@example.com", "phone_number": "17326138213", "example_property": "valueB" } ] }' The call above was extracted from Postman as a fetch API call. – Khalid Apr 22 '21 at 15:21
  • The only difference I see between those two requests is the `Accept` header. And from what I get from the docs, the `xxx_api_key` header should actually look like `api_key: xxx_api_key` but that doesn't seem to be aproblem, because the api key can also be put in the body. – derpirscher Apr 23 '21 at 06:17

0 Answers0