weixin_33698043 2016-08-05 22:57 采纳率: 0%
浏览 66

从CURL到AJAX XMLHttp

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!

  • 写回答

1条回答 默认 最新

  • weixin_33716154 2016-08-05 23:19
    关注

    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
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog