Join 34,000+ subscribers and receive articles from our blog about software quality, testing, QA and security.
 

OPTIONS preflight error in Chrome


#1

I have a React app where I’m trying to make calls to the TestRail API using JavaScript. The following is the snippet of what I’m using:

var projectNumber = 1
let host = "https://myorg.testrail.com"
let uri = '/index.php?/api/v2/'
var url = host + uri 
let username = "myuser@myemail.com"
let testRailKey = 'myApiKey'
var xhttp = new XMLHttpRequest();

xhttp.open("GET", url + "get_project/" + projectNumber, true,
username,testRailKey);

xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('X-Requested-With', 'API Client');

xhttp.send();
var response = JSON.parse(xhttp.responseText);
console.debug(response)

In Chrome it fails on the OPTIONS preflight call with a 400 bad request and following response

{error: "Content-Type header missing (use Content-Type: application/json)"}

and the console reports:

Failed to load https://myorg.testrail.com/index.php?/api/v2/get_project/33: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access. The response had HTTP status code 400.

I’ve tried adding the following headers based on research and other questions, but none seem to make a difference.

xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
// also tried xhttp.setRequestHeader('Access-Control-Allow-Origin','*')
xhttp.setRequestHeader( 'Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
xhttp.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
xhttp.setRequestHeader('X-Requested-With', 'API Client');

Thinking maybe it was my implementation, I am fairly new to React and rusty at JavaScript, I decided to try and use npm package testrail-api (https://www.npmjs.com/package/testrail-api) and I get the same here through that.

How do I get past this?