我目前正在研究一个使用bing图像搜索api的学校项目。我的目标是(尽可能准确地)获取每个《星球大战》角色的头像。我不明白为什么,但是api似乎找不到带有重音符的结果。
例如,在下面的代码中,当searchTerm = "Han Solo"
一切正常时,但是当searchTerm = "Dormé"
时,API不返回任何图片。
更奇怪的是,如果我直接在bing中进行相同的搜索,它会找到很多图片,但是我从API中找不到任何图片。
//server.js
app.get('/getPortrait/*', (req, res) => {
const serviceKey = "MY_KEY";
let searchTerm = req.url.split('/').pop();
// when searchTerme= "han solo", it works fine
// when searchTerme= "Dormé", it works but returns no image in the response
let credentials = new CognitiveServicesCredentials(serviceKey);
let imageSearchClient = new Search.ImageSearchClient(credentials);
let resultURL;
const sendQuery = async () => {
return await imageSearchClient.imagesOperations.search(searchTerm);
};
sendQuery().then(imageResults =>{
console.debug(imageResults)
if (imageResults == null || imageResults.value.length == 0) {
console.error("No image results were found.");
res.send(defaultPic);
}
else {
resultURL = imageResults.value[0].contentUrl;
console.log(resultURL);
res.send(resultURL);
}
}).catch(err => {
console.error(err)
res.send(defaultPic);
});
});
是否可以将搜索配置为接受所有类型的字符?
这是这些查询的结果:
\\searchTerm = "Dormé"
Object {_type: "Images", value: Array(0)}
_type:"Images"
value:Array(0) []
__proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , …}
\\searchTerm = "han solo"
Object {_type: "Images", readLink: "https://api.cognitive.microsoft.com/api/v7/images/…", webSearchUrl: "https://www.bing.com/images/search?q=han%20solo&FO…", totalEstimatedMatches: 868, nextOffset: 43, …}
nextOffset:43
readLink:"https://api.cognitive.microsoft.com/api/v7/images/search?q=han%20solo"
totalEstimatedMatches:868
value:Array(35) [Object, Object, Object, …]
webSearchUrl:"https://www.bing.com/images/search?q=han%20solo&FORM=OIIARP"
__proto__:Object {constructor: , __defineGetter__: , __defineSetter__: , …}
https://www.starwarsnewsnet.com/wp-content/uploads/2017/01/Alden-Ehrenreich-as-Han-Solo-4.jpg
谢谢您的帮助:)
答案 0 :(得分:0)
该问题与Bing Image直接搜索无关,不幸的是,您打开了一堆可爱的蠕虫,它们围绕着node.js(以及整个网络)中的字符编码
为演示此问题,请首先编写方法的简单版本:
app.get('/getPortrait/*', (req, res) => {
const serviceKey = "MY_KEY";
let searchTerm = req.url.split('/').pop();
// when searchTerme= "han solo", it works fine
// when searchTerme= "Dormé", it works but returns no image in the response
// will return Dorm%C3%A9
res.send(searchTerm);
});
Dorm%C3%A9
是Dormé的URL编码版本,当您在URL栏中键入浏览器时,它会自动生成。您可以使用在线url解码网站(例如https://urldecode.org/?text=Dorm%25C3%25A9&mode=decode
因此,您需要使用decodeURI函数在代码中对该值进行解码。
const sendQuery = async () => {
return await imageSearchClient.imagesOperations.search(decodeURI(searchTerm));
};
现在请求http://localhost:3000/getPortrait/Dorm%C3%A9
的返回以下内容: