Json returning null JavaScript



我正在尝试读取一些 YouTube json 数据,但由于某种原因它在控制台中返回 null。

我正在尝试从此链接中检索信息: https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=2MpUj-Aua48&format=json

前端代码:

var title;
var videoId;
var jsonObj;
ytVideoTitle(title, videoId).then(function(result) { jsonObj = 
JSON.parse(result); console.log(jsonObj); });

这是因为标题没有嵌套在html下。尝试

.then(json => console.log(json.html))

.then(json => console.log(json.title))

如果你像这样调用你的代码:

var title; 
var videoId; 
ytVideoTitle(title, videoId).then(function(result) { console.log(result); });

你应该有这样的后端代码:

import {fetch} from 'wix-fetch';
export function ytVideoTitle(title, videoId) {
return fetch("https://www.youtube.com/oembed?url=http://www.youtube.com/watch? v=2MpUj-Aua48&format=json", {method: "get"})
.then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
} ).catch(err => console.log(err));
}

由于您的上一次.then(json => console.log(json.html["title"]))不会返回 JSON 对象,因此您不会将其作为ytVideoTitle函数的返回。

试试这个

`fetch("https://www.youtube.com/oembed?url=http://www.youtube.com/watch? v=2MpUj-Aua48&format=json", {method: "get"})
.then( (httpResponse) => {
if (httpResponse) {
return httpResponse.json();
} else {
return console.log("Fetch did not succeed");
}
} )
.catch(error => console.log(error));`

最新更新