将fetch()与API一起使用
我尝试使用fetch()从中获取数据 这段代码没有定义,但在chrome的“网络”部分,我看到了我需要的数据。我怎样才能访问它将fetch()与API一起使用,api,fetch,Api,Fetch,我尝试使用fetch()从中获取数据 这段代码没有定义,但在chrome的“网络”部分,我看到了我需要的数据。我怎样才能访问它 fetch('https://swapi.co/api/people/1/') .then(resp => resp.json) .then(obj => console.log(obj)); 如果您有合适的环境来调用fetchapi,那么可能会有两个结果 您将获得正确的结果数据 你会得到一个错误 fetch(url) // Call the fetch
fetch('https://swapi.co/api/people/1/')
.then(resp => resp.json)
.then(obj => console.log(obj));
如果您有合适的环境来调用fetchapi,那么可能会有两个结果
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch (function() {
// This is where you run code if the server returns any errors
});
使用catch查看您的请求出了什么问题Hello这将获取以json形式返回的数据
fetch('https://swapi.co/api/people/1')
.然后(功能(响应){
返回response.json();
})
.then(函数(myJson){
log(JSON.stringify(myJson));
});代码>我在chrome的“控制台”部分得到了:ƒjson(){[本机代码]},这意味着我得到了一个结果,但我不知道如何访问chrome的“网络”部分中看到的数据。好的,我理解你。这在chrome中是正常的,但您的客户端有一个错误。捕获会告诉你什么是原因。在catch上调试它。例如,它可能需要一个额外的toJson,但你必须确保看到例外我的朋友谢谢你的帮助。我的错误是我忘了在resp.json()中使用(),这是额外的json:)