有没有办法用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":"Failed to create 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。
任何想法都会有帮助。我已经死在水里了。
最佳答案
从您的代码来看,您似乎正在向 https://api.mongohq.com/databases/vehicles/collections/rockets/documents?_apikey=12345 发送
包含 POST
请求{"document": {"_id": "bottle", "pilot_name": "Elton John"}, "safe": true }
数据和 Content 的 URL -Type
header 设置为 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 }');
关于cURL 请求的 Javascript 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299818/