**已关闭。**此问题需要debugging details。当前不接受答案。
编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
昨天关门了。
Improve this question
我使用谷歌API来拉取某组项目的图像地址。每当我在终端中运行代码时,“节点C:\Users\rest_of_file_name\get_image_url.mjs”
它返回“fetch不是函数”。
我的节点版本:v18.15.0。
下面是我的代码:
/**
* @param {string} searchTerm - Search term for Google Image search.
* @param {function(string,number,number)} callback - Called when an image has
* been found. The callback gets the URL, width and height of the image.
* @param {function(string)} errorCallback - Called when the image is not found.
* The callback gets a string that describes the failure reason.
*/
import fetch from "node-fetch";
const key = 'flkfjslksj';
const cx = 'sfkjlkfjlk';
function getImageUrl(searchTerm, callback, errorCallback) {
var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
'?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);
import('node-fetch')
.then(fetch => {
return fetch(searchUrl);
})
.then(res => res.json())
.then(json => {
var response = json;
if (!response || !response.items || response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
var firstResult = response.items[0];
var imageUrl = firstResult.link;
var width = parseInt(firstResult.image.width);
var height = parseInt(firstResult.image.height);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height);
})
.catch(error => {
errorCallback(error.message);
});
}
const items = ['Fine Line', 'Lemon Boy', 'The Life of Pablo'];
for (const item of items) {
getImageUrl(item, function (imageUrl, width, height) {
console.log(imageUrl, width, height);
}, function (errorMessage) {
console.error(errorMessage);
});
}
我认为这与fetch函数有关,只是不知道如何修复它。
它实际上成功地工作了一次。但是,当我再次运行它而不做任何更改时,我得到了fetch不是一个函数的错误。
1条答案
按热度按时间4nkexdtk1#
将所有导出作为一个对象导入,并作为参数传递给
then
回调。实际的函数是default
导出。访问它的一种方法是命名析构函数另一种方法是使用顶级
fetch
并删除动态导入。没有理由同时使用两个导入。您应该选择一个并删除另一个。顶级导入有一些优点,例如树抖动。