为了摆脱 Ajax 调用,我更改了代码以使用 Javascript Fetch API非常干净。
在下面的示例中,我必须注释掉请求的 body
获取选项,并将 method 选项更改为 GET
。
我这样做是为了看看它是否有效,并且......它确实有效。
现在我想知道如何将 body
获取选项参数传递给请求。
最后,我遇到了一个名为 AbortController Interface 的问题。并且想知道您是否可以向我展示如何在下面的示例中实现它,或者它是否根本无法从中受益。
谢谢
// POST DATA
function postData(url = 'https://api.myjson.com/bins/elr1f', params = [{param1Key: 'param1Val'}]) {
const fetchOptions = {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type', 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
// body: JSON.stringify(params), // body data type must match "Content-Type" header
};
// Default fetchOptions are marked with *
return fetch(url, fetchOptions)
.then(function(response) {
// RESPONSE VALIDATION
switch (response.status) {
case 200:
// code...
console.info('HTTP response status: 200 OK');
return response;
break;
case 404:
// code...
throw new Error('HTTP response status: 404 Not Found.');
break;
case 500:
// code...
throw new Error('HTTP response status: 500 Internal Server Error.');
break;
case 503:
// code...
throw new Error('HTTP response status: 503 Service Unavailable.');
break;
default:
// code...
break;
}
})
// parse JSON response into native JavaScript object(s)
.then (response => response.json() )
// access the node we want
.then (response => console.info(response.users) )
// catch a freaking error
.catch(error => console.error(error) );
}
<button onclick="postData()">GET USERS</button>
最佳答案
GET 请求,只能在 URL 中指定参数,不应该有正文...
通过 POST 请求,您可以 supply parameters in the body. POST 请求的行为与 GET 请求类似,没有问题。
关于javascript - 使用数组参数获取 API GET 请求。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661136/