Is there a way to complete this cURL request in Javascript?
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 }'
The below code is as close as I've been able to get, but it returns {"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();
}
I get a 500 error when I execute this, but the cURL works fine. I assume it's an issue with setting the content type. Is there a way to set the content type in the form or post object? It seems mongohq requires an explicit content type declaration.
I don't have access to change the same-origin policy on the server, and I'm pretty sure I won't be able to execute PHP.
Any thoughts would be helpful. I'm dead in the water here.
From your code, it looks like you are sending a POST
request to https://api.mongohq.com/databases/vehicles/collections/rockets/documents?_apikey=12345
URL with {"document" : {"_id" : "bottle", "pilot_name" : "Elton John"}, "safe" : true }
data and the Content-Type
header set to application/json
.
This can be achieved in JavaScript by doing the following
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 }');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.