1

I am trying to call the api TextRazor (https://www.textrazor.com/docs/rest#introduction) which has examples in curl, php, python and Java. However I would like to do it with jquery ajax.

On the website we can see an example in curl:

curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off its vast portfolio of industrial holdings that includes a stake in the parent company of British Airways and Iberia." \
https://api.textrazor.com/

Here is how I am working to pass it through ajax

var txt = "Spain's stricken Bankia expects to sell off its vast portfolio of industrial holdings that includes a stake in the parent company of British Airways and Iberia.";

$.ajax({
  url: "https://api.textrazor.com/",
  type: "POST",
  headers: {
    "x-textrazor-key": "my-api-key"
  },
  data: {
    extractors: 'entities',
    text: txt
  },
  success: function(data) {
    console.log(data);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

But all the time is sending 400 (Bad Request) error which means that the syntax is wrong.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Adrian Vazquez
  • 327
  • 1
  • 6
  • 20
  • 1
    If you look closely, your JS syntax is invalid with a single quote in your `txt` string. You are also missing an element in your `extractors` field. Furthermore, depending on the server's configuration, you might have to pass your data as raw payload or as a form. – Derek 朕會功夫 Feb 13 '18 at 14:57
  • 2
    You should note that unless the server is configured to pass the `Access-Control-Allow-Origin` header, you will probably be blocked by the browser's CORS policy. The other methods you listed above _cURL_, _PHP_, _Python_ and _Java_ typically run server side and are except from this policy... – War10ck Feb 13 '18 at 15:00
  • 1
    I placed your code in an executable snippet. If you check the console of that snippet you can see the issue is due to the lack of CORS headers in the response as @War10ck surmised. Given that restriction, you cannot make the request directly from JS. You'll need to proxy it using cURL on the server side. – Rory McCrossan Feb 13 '18 at 15:05
  • Actually this "txt" is an example. I am getting the text from a DIV with JavaScript for that reason I wanted to do the call in the same language. Therefore I guess I need to use the JavaScript to get the txt anyway and then call it with php. Like =.js (get the text) -> php (call the api) -> js (put it back into div) – Adrian Vazquez Feb 13 '18 at 15:58

0 Answers0