详情介绍
javascript
// 创建一个插件对象
var myPlugin = {
// 定义一个方法来调用API
callApi: function(url, callback) {
// 使用fetch API发起HTTP请求
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => callback(null, data))
.catch(error => callback(error));
}
};
// 使用插件
myPlugin.callApi('https://api.example.com/data', function(err, data) {
if (err) {
console.error('Error calling API:', err);
} else {
console.log('API response:', data);
}
});
在这个示例中,我们创建了一个名为`myPlugin`的插件对象,其中包含一个名为`callApi`的方法。这个方法接受两个参数:一个是API的URL,另一个是回调函数。我们使用`fetch` API发起HTTP请求,并将响应转换为JSON格式。最后,我们将结果传递给回调函数。