[英]How to Fetch API (POST) using one single url but with each 4 different parameters
好的,我還是Javascript的新手。 根據標題,如何獲取單個API網址,但有4個不同的參數。 我的目標是顯示4個不同的類別
示例(我有4個不同的類別):
const category = [1,2,3,4];
我想讓每個類別都要求api
方法1
要撥打第1類:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=1`
};
fetch(url, options)
.then(response => response.json())
.then(object => {})
要打電話給第2類:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=2`
};
fetch(url, options)
.then(response => response.json())
.then(object => {})
要打電話給第3類:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=3`
};
fetch(url, options)
.then(response => response.json())
.then(object => {})
要打電話給第4類:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=4`
};
fetch(url, options)
.then(response => response.json())
.then(object => {})
或許我可以簡化它們:
方法2
const parameter1 = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=1`
};
const parameter2 = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=2`
};
const parameter3 = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=3`
};
const parameter4 = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `USERID=userid&TOKEN=usertoken&CATEGORY=4`
};
Promise.all([
fetch(url,parameter1).then(value => value.json()),
fetch(url,parameter2).then(value => value.json()),
fetch(url,parameter3).then(value => value.json()),
fetch(url,parameter4).then(value => value.json()),
])
.then((value) => {
console.log(value)
//json response
})
.catch((err) => {
console.log(err);
});
但所有這些都是非常多余和不必要的重復。 如果我有50個類別怎么辦? 如何簡化所有這些Fetch API調用? 請給我一個啟發。 提前致謝
你可以更進一步。 由於您的方法,標題和正文的一部分都是相同的,因此只需將其提取到一個函數即可。 自定義構建類別的參數,然后調用fetch
。
const thatPostFunction = category => {
const method = 'POST'
const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
const body = `USERID=userid&TOKEN=usertoken&CATEGORY=${category}`
return fetch(url, { method, headers, body })
}
const categories = [...category ids...]
const promises = categories.map(c => thatPostFunction(c))
Promise.all(promises)
.then((value) => {
console.log(value)
//json response
})
.catch((err) => {
console.log(err);
});
您可以創建一個運行所有這些功能的函數:
const categories = [1,2,3,4]; const postUrls = (items) => { const promises = [] items.forEach(item => { const url = 'http://www.myapiurl.com/thisapi'; const options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `USERID=userid&TOKEN=usertoken&CATEGORY=${item}` }; const prms = fetch(url, options) .then(response => response.json()) promises.push(prms) }) return Promise.all(promises) } postUrls(categories) .then(data => console.log('Done!'))
我會編寫一個函數將類別id轉換為Promise,然后編寫一個包裝函數將類別ID數組轉換為一個解析為fetch結果數組的Promise:
const fetchCategory = (catId) => { const url = 'http://www.myapiurl.com/thisapi'; const options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `USERID=userid&TOKEN=usertoken&CATEGORY=${catId}` }; return fetch(url, options) .then(response => response.json()) } const fetchCategories = (categories) => Promise.all(categories.map(fetchCategory)) const categories = [1, 2, 3, 4] fetchCategories(categories).then(categoryResults => { // here categoryResults is an array of the fetch results for each category. console.log(categoryResults) })
<script> // Faking out fetch for testing const fetch = (url, opts) => Promise.resolve({ json: () => ({ categoryId: `${opts.body.slice(opts.body.lastIndexOf('=') + 1)}`, more: 'here' }) }) </script>
如果您的API非常靈活,那么您可以同時詢問所有4個類別。 我見過API這樣做:
body: `USERID=userid&TOKEN=usertoken&CATEGORY=1,2,3,4`
我看到他們這樣做:
body: `USERID=userid&TOKEN=usertoken&CATEGORY=1&CATEGORY=2&CATEGORY=3&CATEGORY=4`
同樣,您的API需要能夠枚舉類別並將結果返回到某種對象或數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.