使用POST的JQuery ajax从启用CORS的服务器获取image / png

时间:2013-10-30 16:17:43

标签: jquery ajax post cross-domain cors

我正在编写一个HTML5 / Backbone / Phonegap应用Github Repo,该应用使用SensornbservationService REST API 52n(v1 API Docs)。 每个GET-Request工作正常 - 但现在我想下载一个POST请求后生成的图片。

但是服务器响应状态400:

statusCode":400,"hints":["Check the message which has been sent to the server. Probably it is not valid."],"reason":"Bad Request","developerMessage":"Could not read JSON ...

这是我的AJAX-Call:

var body = {
    "base64":true,
    "legend":false,
    "timespan":"2013-10-30T00:00:00Z/2013-10-30T23:59:59Z",
    "width":482,
    "height":568,
    "language":"en",
    "grid":false,
    "styleOptions": {
        "ts_32e1174948e46f2e46fe597eb40b3557": {
            "chartType": "line",
            "properties": {
                "color": "#b45e87",
                "lineType":"solid",
                "width":1
            }
        }
    }
};
$.support.cors = true;

this.xhr = $.ajax({
     crossDomain: true,
     type: "POST",
     url:"http://sensorweb.demo.52north.org/sensorwebclient-webapp-stable/api/v1/timeseries/getData",
     processData: false,
     dataType: "json",
     accept: "application/json",
     contentType:  "application/json; charset=utf-8",
     data: body
   }).done(function(data) {
   }).fail(function(xhr, textStatus) {
   }).always(function() {
   });

这是我的fiddle - 如果我尝试使用POSTMAN进行相同的POST调用,服务器会按照自己的意愿进行操作。

RESTClient实现-截图 Screenshot with working Call in RESTClient

我的电话有什么问题?

1 个答案:

答案 0 :(得分:3)

这是52n API中的一个错误 - 感谢52n - 现在修复了。 这是解决方案:

$.support.cors = true;
this.xhr = $.ajax({
    crossDomain: true,
    type: "POST",
    url: "http://sensorweb.demo.52north.org/sensorwebclient-webapp-stable/api/v1/timeseries/getData",
    headers: {
        "accept": "image/png",
            "content-Type": "application/json",
    },
    data: JSON.stringify(body)
}).done(function (data) {
    $('#output').html('<img src="data:image/png;base64,' + data + '" />');
});

- &GT; JSFiddle