根据https://developer.mozilla.org/en-US/docs/Web/API/Request。以下代码片段可以在JavaScript中构造POST请求实例。
var myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});
var myURL = myRequest.url; // http://localhost/api
var myMethod = myRequest.method; // POST
var myCred = myRequest.credentials; // omit
var bodyUsed = myRequest.bodyUsed; // true
但是在我的Chrome浏览器中,我得到了一个没有正文的实例但实际上我将选项与body一起传递给了Request
。
那么如何构建POST请求呢?
答案 0 :(得分:0)
由于请求仍处于试验阶段,我会使用XMLHttpRequest发出POST请求。
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
答案 1 :(得分:0)
可能并非MDN Request都记录了所有内容。我复制了OP样本,但是当我添加下一段的代码时,结果是不同的。
function doReq() {
var myRequest = new Request('json.php', { method: 'POST', body: '{"foo":"bar"}' });
console.log(myRequest);
//return; //when uncommented returns bodyUsed: false
//when commented bodyUsed: true and body goes to the server
console.log(JSON.stringify(myRequest)); //{} all the time
fetch(myRequest)
.then(function(response) {
if(response.status == 200) return response.json();
else throw new Error('Something went wrong on api server!');
})
.then(function(response) {
console.debug(response);
// ...
})
.catch(function(error) {
console.error(error);
});
}
测试用例:
FF 47.0.1 - 如上所述。
谷歌Chrome 51 - 如上所述
边缘 - '请求'未定义(如预期的那样)
答案 2 :(得分:0)
根据https://developer.mozilla.org/en-US/docs/Web/API/Request。请求没有body属性。因此,您无法在Chrome控制台日志中看到它。
但是你的请求确实有body属性,你可以实际使用它。当我获取请求时,我实际上得到了身体。这是我的测试结果。 test result
如果您还有其他问题,请发表评论。