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

标签 javascript ajax rest

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

我试图用这段代码来做到这一点:

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

最佳答案

您必须将 content-type header 设置为 application/json
您将 json 数据作为 formdata 发布,这是错误的
(在您旁边忘记对你的对象进行字符串化)

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

这是一个使用新的 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
})

关于javascript - REST API - Vanilla JavaScript/AJAX 中的 POST 方法 - 错误 400(错误请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45013259/

相关文章:

java - Jersey Api 未通过过滤器发送请求

javascript - 检索jquery附加的div

javascript - 等待 window.location.href?

javascript - 如何使用 es6 String.raw 打印 '\1'

javascript - 表单验证并提交ajax

php - Codeigniter RESTful API-{"status":false ,"error" :"Unknown method."}

javascript - noscript 标签在不同浏览器中的处理方式

javascript - jQuery ajax 成功方法在 ie8 中有效,但在 ie9 中无效?

php - 具有 AJAX 异步工作的 JQuery 加载器 :false

asp.net - 在 IIS 上使用 Http 管道进行 Rest