1

有没有办法在 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。

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

4

1 回答 1

0

从您的代码看来,您正在向URL发送一个POST请求,其中包含数据且标头设置为.https://api.mongohq.com/databases/vehicles/collections/rockets/documents?_apikey=12345{"document" : {"_id" : "bottle", "pilot_name" : "Elton John"}, "safe" : true }Content-Typeapplication/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 }');

于 2018-06-21T07:19:10.563 回答