Request header field apikey is not allowed by Access-Control-Allow-Headers in preflight response

941 Views Asked by At

I am trying to test the tone analyzer of IBM watson with JavaScript code (fetch API).

Here's my code:

async post(url,key,textData)
{
        
    const response1 = await fetch(`https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&statements=false`,{
        method: 'POST',
        headers: 
        {
            'Content-type': 'application/json',
            'apikey':'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
        },
        body: JSON.stringify(textData)
    });
    
    const responseData = await response1.json();
    return responseData;
    console.log(responseData);
    }

Now, this particular code throws error:

Failed to load https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&statements=false: Request header field apikey is not allowed by Access-Control-Allow-Headers in preflight response.

I checked this using the postman tool and it works fine.

I have faced a similar issue with https://openweathermap.org/api when using XMLHttpRequest and it did not occur again while using fetch.

Can I get some pointers on

  1. What can be the difference here with the postman and a simple javascript code?
  2. How to overcome these errors in future?
1

There are 1 best solutions below

0
On

This is a classic CORS restriction. Postman works as it is not classed as a browser but as an application with a REST Client.