cURL 请求的 Javascript 等效项

标签 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":"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/

相关文章:

javascript - Nervgh Angular 文件上传 - 如何限制要上传的图像数量?

php - 为什么 CodeIgniter 的 Curl 库比在纯 PHP 中使用 Curl 慢?

必须加载 php 扩展 mcrypt

linux - 在 Linux 机器上安装 cURL 时出错

javascript - 如何在 Mapbox GL JS 中添加自定义地理定位我按钮?

javascript - 悬停时动画

javascript - 在chartjs中查找图表线之间的交点

java - 如何从 php 向 java/android 发送和检索数据?

php - 如何使用 PHP 制作 pdf 文件

ssl - gitLab 更新 : curl returns ssl error 35