看来我太笨了或者只是盲目,因为我无法做到这一点。
我的其他 Google API(图书 API)非常有用。
使用 JSON 风格的返回数据很容易。
但是 Google 的这个“知识图搜索 API”返回 JSON-LD 风格的数据。
在浏览器中按 URL 执行此操作可以按预期工作:
https://kgsearch.googleapis.com/v1/entities:search?query=LoremIpsum&key=VUE_APP_GOOGLE_API_KEY&ident=True
类似这样的:
{
"@context": {
"goog": "http://schema.googleapis.com/",
"resultScore": "goog:resultScore",
"EntitySearchResult": "goog:EntitySearchResult",
"detailedDescription": "goog:detailedDescription",
"kg": "http://g.co/kg",
"@vocab": "http://schema.org/"
},
"@type": "ItemList",
"itemListElement": [
{
"result": {
"@id": "kg:/g/11f266hnh5",
"name": "Blupp",
"@type": [
"Thing"
],
"description": "Song by Jan Garbarek Quartet"
},
"@type": "EntitySearchResult",
"resultScore": 46.472198486328118
},
{
"@type": "EntitySearchResult",
"result": {
"name": "Bluppo",
"@type": [
"VideoGame",
"CreativeWork",
"SoftwareApplication",
"Thing"
],
"@id": "kg:/m/097m49",
"description": "Arcade game"
},
"resultScore": 19.4659481048584
},
现在在 vue3 中:
我的输入栏:
<td class="inputField">
<input @keyup.enter="search" v-model="this.inputTitle" id="global-input" type="text" placeholder="Freitext"/>
</td>
我的搜索功能
<script>
import { globalSearch } from "../api/films-api.js";
....
methods: {
async search() {
await globalSearch(this.inputTitle).then((response) => {
if (response.items) {
this.films = response.item;
} else {
this.films = {};
}
});
},
我的
globalSearch
功能
export async function globalSearch(query) {
return new Promise((resolve, reject) => {
console.log("url: " + BASE_URL +
query +
"&" +
key + process.env.VUE_APP_GOOGLE_API_KEY + "&" +
indent + "True");
fetch(BASE_URL +
query +
"&" +
key + process.env.VUE_APP_GOOGLE_API_KEY + "&"+
indent + "True"
)
.then((response) => {
resolve(response); // <- a promise Object I can't work with
})
.catch((err) => {
console.log("err: " + err.message);
reject(err.message);
});
});
}
我可以用此回复做什么?
console.log(response);
[对象响应] 2. 当我这样做时
json.parse(response)
错误:JSON.parse:JSON 数据第 1 行第 2 列出现意外字符 3.解决(响应)
> 给我:未定义
我所需要的只是标签
'"itemListElement":'
和下面的标签来读出“结果”块。npm install jsonld
)。resolve(response.json());
当在下面的函数中打印到控制台 vie console.log 时,仍然未定义。
export async function globalSearch(query) {
return new Promise((resolve, reject) => {
console.log("url: " + BASE_URL + query + "&" + key + process.env.VUE_APP_GOOGLE_API_KEY + "&"+ indent + "True");
fetch(BASE_URL +
query +
"&" +
key + process.env.VUE_APP_GOOGLE_API_KEY + "&"+
indent + "True"
)
.then((response) => {
resolve(response.json());
})
.catch((err) => {
reject(err.message);
});
});
}
但是
response.itemListElements
恰好保存了我需要的数据。
async search() {
await globalSearch(this.inputTitle).then((response) => {
console.log("response.itemListElement: " + response.itemListElement);
if (response.itemListElement) {
this.films = response.itemListElement;
} else {
this.films = {};
}
})
},