REST API - Vanilla JavaScript / AJAX中的POST方法 - 错误400(错误请求)

时间:2017-07-10 13:24:13

标签: javascript ajax rest

你能帮助我如何在vanilla JS(没有jQuery)中使用POST方法吗?

我正在尝试使用此代码:

var call =
{
  "filterParameters": {
    "id": 18855843,
    "isInStockOnly": false,
    "newsOnly": false,
    "wearType": 0,
    "orderBy": 0,
    "page": 1,
    "params": {
      "tId": 0,
      "v": []
    },
    "producers": [],
    "sendPrices": true,
    "type": "action",
    "typeId": "",
    "branchId": ""
  }
};
var xhr = new XMLHttpRequest();

xhr.open('POST', 'https://www.alza.cz/Services/RestService.svc/v2/products');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log('OK ' + xhr.responseText);
    }
    else if (xhr.status !== 200) {
        console.log('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send(call);

不断收到错误400(错误请求)。 我试图在jQuery中调用它并且它正在工作,但我需要在普通JS中使用它。

请知道为什么它不起作用?

查看,这是jQuery中的工作代码:

addData({
  "filterParameters": {
    "id": 18855843,
    "isInStockOnly": false,
    "newsOnly": false,
    "wearType": 0,
    "orderBy": 0,
    "page": 1,
    "params": {
      "tId": 0,
      "v": []
    },
    "producers": [],
    "sendPrices": true,
    "type": "action",
    "typeId": "",
    "branchId": ""
  }
}
);

function addData(data){// pass your data in method
     $.ajax({
             type: "POST",
             url: "https://www.alza.cz/Services/RestService.svc/v2/products",
             data: JSON.stringify(data),// now data come in this function
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {

                 console.log(data);// write success in " "
             },

             error: function (jqXHR, status) {
                 // error handler
                 console.log(jqXHR);
                 alert('fail' + status.code);
             }
          });
    }

3 个答案:

答案 0 :(得分:2)

您必须将content-type标题设置为application/json
您将json数据作为formdata发布,这是错误的(除了您忘记对字符串进行字符串化)

xhr.setRequestHeader('Content-Type', 'application/json');

Heres是一个使用新的vanilla js fetch API的工作示例

var result = null

fetch("https://www.alza.cz/Services/RestService.svc/v2/products", {
  method: "POST",
  body: JSON.stringify({
    "filterParameters": {
      "id": 18855843,
      "isInStockOnly": false,
      "newsOnly": false,
      "wearType": 0,
      "orderBy": 0,
      "page": 1,
      "params": {
        "tId": 0,
        "v": []
      },
      "producers": [],
      "sendPrices": true,
      "type": "action",
      "typeId": "",
      "branchId": ""
    }
  }),
  headers: {"content-type": "application/json"},
  //credentials: 'include'
})
.then(function(res) {
  if (res.ok) { // ok if status is 2xx
    console.log('OK ' + res.statusText);
  } else {
    console.log('Request failed.  Returned status of ' + res.status);
  }

  return res.blob()
})
.then(function(blob) {
  result = blob
  // window.result = blob
})

答案 1 :(得分:0)

Access-Control-Allow-Origin响应阻止Javascript代码访问服务器数据。如果服务器不受您控制,则需要另一台服务器来获取数据,然后才能重定向到您的网页。

答案 2 :(得分:0)

所以我只是尝试了xhr.send()

得到了

XMLHttpRequest cannot load https://www.alza.cz/Services/RestService.svc/v2/products. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://www.alza.cz' that is not equal to the supplied origin.

但是,如果我在空白标签上尝试此操作,它实际上是有效的。 你试图从哪个URL运行这个JS?

尝试从空白标签运行JS。