繁体   English   中英

等同于cURL请求的Javascript

[英]Javascript Equivalent of a cURL request

有没有办法用Javascript完成此cURL请求?

curl -X POST https://api.mongohq.com/databases/vehicles/collections/rockets/documents?_apikey=12345 \
-H "Content-Type: application/json" \
-d '{"document" : {"_id" : "bottle", "pilot_name" : "Elton John"}, "safe" : true }'

下面的代码已尽我所能,但它返回{“ error”:“无法创建mongohq :: api :: document”}。

function postsBeaconMessage (postTo, beaconMessage , targetFrame) {
    var beacon = document.createElement("form");
    beacon.method="POST";
    beacon.action = postTo;
    //beacon.target = targetFrame;

    var message = document.createElement("input") ;
    message.setAttribute("type", "hidden") ;
    message.setAttribute("name", "document") ;
    message.setAttribute("value", beaconMessage);
    beacon.appendChild(message) ;

    beacon.submit();
}

执行此操作时出现500错误,但是cURL可以正常工作。 我认为设置内容类型是一个问题。 有没有一种方法可以在表单或发布对象中设置内容类型? 似乎mongohq需要明确的内容类型声明。

我无权更改服务器上的同源策略,而且我很确定我将无法执行PHP。

任何想法都会有所帮助。 我死在这里的水中。

从您的代码看来,您正在将POST请求发送到https://api.mongohq.com/databases/vehicles/collections/rockets/documents?_apikey=12345带有{"document" : {"_id" : "bottle", "pilot_name" : "Elton John"}, "safe" : true } URL {"document" : {"_id" : "bottle", "pilot_name" : "Elton John"}, "safe" : true }数据,并将Content-Type标头设置为application/json

可以通过执行以下操作在JavaScript中实现

 let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { // Check if request is completed if (xhr.readyState == XMLHttpRequest.DONE) { // Do what needs to be done here console.log(xhr.response); } } // Set the request URL and request method xhr.open("POST", "https://api.mongohq.com/databases/vehicles/collections/rockets/documents?_apikey=12345"); // Set the `Content-Type` Request header xhr.setRequestHeader("Content-Type", "application/json"); // Send the requst with Data xhr.send('{"document" : {"_id" : "bottle", "pilot_name" : "Elton John"}, "safe" : true }'); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM