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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀