0

I'm trying to convert the curl code from an API called TextRazor to AJAX XMLHttp because of platform limitations. I have tried many solutions from similar questions by the community but can't seem to get any data back or just a "400: Bad Request". If it matters, from the documentation calling the API looks like this:

curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off..." \
https://api.textrazor.com/

My current AJAX XMLHttp code looks like this:

var xhttp = new XMLHttpRequest();
var url = "https://api.textrazor.com/";
var params = "extractors=entities&text=Spain's stricken Bankia expects to sell...";
xhttp.open("POST", url, true);

xhttp.setRequestHeader("x-textrazor-key", "YOUR_API_KEY");
xhttp.setRequestHeader("Content-length", params.length);

xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
    alert(xhttp.responseText);
}
}

xhttp.send(params);

Thanks for your support!

JorgeC
  • 615
  • 3
  • 7
  • 13

1 Answers1

0

You are running into the same origin policy.

Because you are making a cross-origin request and adding a custom header, the browser is making a preflight OPTIONS request before it makes the request you are asking for.

The server you are making the request to is not prepared to respond to an OPTIONS request so it throws a 400 back at you.

To fix this:

  • They should support CORS
  • They should provide an alternative means to get the data such as JSONP (not recommended, we have CORS now)
  • You should not make the request directly to their server from the browser
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335