Javascript等效的cURL请求

时间:2013-10-10 15:19:09

标签: javascript php curl

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

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

1 个答案:

答案 0 :(得分:0)

从您的代码看来,您正在向POST URL发送https://api.mongohq.com/databases/vehicles/collections/rockets/documents?_apikey=12345请求,其中包含{"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 }');