Keep getting Unsupported Media Type Error

487 views Asked by At

My UI keeps getting an unsupported media type error when trying to get a response from an endpoint.

Postman actually gets a success using the same body and headers, hence I really don't understand what is the issue, will try anything at this point.

I tried giving the headers all possible values : "text/plain", "text/json" ect... . I defined the "Accept" key to "*".

Here's my code:

  const getProducts = async () => {
    try {
      const response = await fetch(
        "https://dcsquare-utilities.chubb.com:472/CentralizedEnvControlAPI/GetProducts",
        // "https://dummyjson.com/products/1",
        {
          method: "post",
          mode: "no-cors",

          headers: {
            "Content-Type": "application/json",
            "Accept": "*/* ",
            "Accept-Encoding": "gzip, deflate, br"
            // "Access-Control-Allow-Origin": "*"
          },
          body: JSON.stringify(body),
        }
      );
      const data = await response.json();
      console.log("G", data);
    } catch (err) {
      console.error(err);
    }
  };

  1. The UI Error:

enter image description here

  1. Postman headers and success:

enter image description here

1

There are 1 answers

3
Isaac Reynaldo On

Remove the no-cors mode: The no-cors mode prevents the browser from sending CORS preflight requests and restricts the headers that can be set in the request. If the server requires specific headers or does not allow cross-origin requests, this may be causing the "unsupported media type" error. Try removing the no-cors mode and see if that resolves the issue.

Also, Postman provides an option to generate code snippets for different programming languages including JavaScript, which you can use to make API requests in your code. Here are the steps to generate JavaScript code in Postman:

  1. Click the "Code" button in the upper right corner of the request builder.

  2. Select "JavaScript" as the language from the dropdown menu.

  3. Postman will generate the JavaScript code for the configured request. You can copy and paste the generated code into your JavaScript file.