【发布时间】:2021-02-02 16:46:41
【问题描述】:
我有一个简单的 Vue.JS 新标签页。我想在我的搜索栏上获得谷歌建议,并进行一些挖掘,我发现了一个我可以从中进行操作的 API。但是,在运行我的代码时:
function retrieveQueries() {
fetch(
`http://suggestqueries.google.com/complete/search?client=chrome&q=cats`
)
.then((res) => res.json()) //failed when just printing res as the default output, or with res.text()
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err);
});
}
但是,当执行时,控制台返回此错误消息:
GoogleSearchBar.vue?69f5:42 TypeError: Failed to fetch
eval @ GoogleSearchBar.vue?69f5:42
Promise.catch (async)
retrieveQueries @ GoogleSearchBar.vue?69f5:40
Object.onInput._cache.<computed>._cache.<computed> @ GoogleSearchBar.vue?69f5:14
callWithErrorHandling @ runtime-core.esm-bundler.js?5c40:154
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js?5c40:163
invoker @ runtime-dom.esm-bundler.js?830f:301
但是当使用 API Tester 时,它会返回:
["cats",["cats","cats for sale","cats for sale in my area","cats for sale UK"],["","","",""],[],{"google:clientdata":{"bpc":false,"tlw":false},"google:suggestrelevance":[1252,650,601,600],"google:suggestsubtypes":[[433,355],[433,457],[402],[402]],"google:suggesttype":["QUERY","QUERY","QUERY","QUERY"],"google:verbatimrelevance":1300}]
此代码与openweathermap API 完美配合,当使用API tester 时,它似乎返回了我想要获取的内容。
我做错了什么,或者有更好的方法吗?
【问题讨论】:
-
tl;dr
suggestqueries.google.com不允许 CORS,因此您要么必须从后端发出请求,要么找到允许 CORS 的 API,或者使用 corsanywhere 之类的东西。 -
使用 corsanywhere 为我解决了这个问题,谢谢您的帮助!
标签: javascript vue.js xmlhttprequest fetch