【问题标题】:How to log the response coming from fetch api如何记录来自 fetch api 的响应
【发布时间】:2019-06-08 07:57:27
【问题描述】:

我正在使用 Promise 记录来自 api 的响应。但是每次身体都以空值登录。很可能是由于异步调用

用于从 fetch 调用 api。

function getDetails(url){
    return new Promise((resolve, reject) => {
        fetch(url, {mode: 'no-cors'}).then(res => {
            resolve(res);      
        }, error => {
            console.log(err);
        })
    })
}

var u = "https://get.geojs.io/v1/ip/country.json";
getDetails(u).then(function(resp){
    console.log(resp);    
})

我期待 api 在控制台中的响应

【问题讨论】:

  • fetch() 已经返回了一个Promise,因此new Promise(...) 是不必要的
  • 如果我只是在函数中执行 fetch 和 .then() 而不返回任何内容,那么 body 仍然是 null
  • fetch() 返回一个Response object
  • function getDetails(url){ fetch(url, {mode: 'no-cors'}).then(res => { console.log(res) ; },error => { console.日志(错误); }) }
  • Trying to use fetch and pass in mode: no-cors 的可能重复项。不要使用“no-cors”模式。

标签: javascript promise request fetch response


【解决方案1】:

fetch() 已经返回了 Promise,所以去掉 new Promise(...) 部分

function getDetails(url) {
    return fetch(...).then(...);
}

fetch() 返回 Response object 而不是已经为您解析的内容。您必须调用.json() 才能获得JSON.parse() 解析的响应。

function getDetails(url) {
    return fetch(url, {mode: 'no-cors'}).then(response => response.json());
}

这应该已经可以了,但是你的设置会抛出一个语法错误:

SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束

要修复此问题,请移除 mode: 'no-cors'

把它们加在一起会给我们:

function getDetails(url) {
    return fetch(url).then(response => response.json());
}

var u = "https://get.geojs.io/v1/ip/country.json";
getDetails(u).then(function(data) {
    console.log(data);
})

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2019-12-30
    • 2017-09-07
    相关资源
    最近更新 更多