库本体
class EasyHTTP {
// Make an HTTP GET Request
async get(url) {
const response = await fetch(url);
const resData = await response.json();
return resData;
}
// Make an HTTP POST Request
async post(url, data) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
});
const resData = await response.json();
return resData;
}
// Make an HTTP PUT Request
async put(url, data) {
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
});
const resData = await response.json();
return resData;
}
// Make an HTTP DELETE Request
async delete(url) {
const response = await fetch(url, {
method: 'DELETE',
headers: {
'Content-type': 'application/json'
}
});
const resData = await 'Resource Deleted...';
return resData;
}
}
export const http = new EasyHTTP();
使用演示
import { http } from './http';
function removeUndefined(word) {
if (word.sphere === undefined) {
word.sphere = '-';
return word.sphere;
} else if (word.origin === undefined) {
word.origin = '-';
return word.origin;
} else if (word.homonym === undefined) {
word.homonym = '-';
return word.homonym;
}
}
function getWords(input) {
http
.get('http://some-site.com')
.then(data =>
data.forEach(function (word) {
// Initialize words_output
let words_output = '';
// Check if a searched word in json matches input
const matchedWord = word.someWord === input;
// Fetch all related words
const related_words = word.related_words;
removeUndefined(word);
if (matchedWord) {
// do something you want
} else {
console.log('No word found');
}
})
)
.catch(err => console.log(err));
}