doushenyu2537 2013-10-10 15:19
浏览 894

Javascript等效的cURL请求

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.

  • 写回答

1条回答 默认 最新

  • douzao9845 2018-06-21 07:19
    关注

    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 }');

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)