gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:04:00 25 4
gpt4 key购买 nike

你能帮我看看如何在 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);
}
});
}

最佳答案

您必须将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com