JS - 获取 API,GET 方法返回“? json() { [native code] }”

问题描述 投票:0回答:3

我想了解两种获取方法之间的区别,一种有效,另一种无效,但我不明白为什么。

这不起作用:

fetch('https://glo3102lab4.herokuapp.com/fee958c0-c320-40d0-a750-218f2d7c1303/tasks', {
    method: 'GET',
}).then(res => res.json)
    .catch(error => {
        console.error('Error:', error);
    })
    .then(response => {
        console.log(response);
    });

并返回:

json() { [本机代码] }

这个效果很好:

fetch('https://glo3102lab4.herokuapp.com/fee958c0-c320-40d0-a750-218f2d7c1303/tasks').then(function(response){
    response.json().then(function(data) {
        console.log(data);
    });
}).catch(function(error) {
    console.log('Fetch Error:', error);
});

并返回:

{任务:数组(4)}任务:(4) [{…}, {…}, {…}, {…}] 原型:对象

如果你想尝试一下:

fetch('https://glo3102lab4.herokuapp.com/fee958c0-c320-40d0-a750-218f2d7c1303/tasks', {
        method: 'GET',
    }).then(res => res.json)
        .catch(error => {
            console.error('Error:', error);
        })
        .then(response => {
            console.log("first way");
            console.log(response);
        });
        
fetch('https://glo3102lab4.herokuapp.com/fee958c0-c320-40d0-a750-218f2d7c1303/tasks').then(function(response){
        response.json().then(function(data) {
            console.log("second way");
            console.log(data);
        });
    }).catch(function(error) {
        console.log('Fetch Error:', error);
    });

javascript fetch-api
3个回答
35
投票

它不起作用,因为您正在返回

res.json
函数。你必须调用它并返回一个 Promise:

.then(res => res.json())

8
投票

.json
是一个函数。你必须调用它。
.then(res => res.json())


0
投票

res.json
正在尝试调用函数,因此请将代码更改为
res.json()
(添加括号)

© www.soinside.com 2019 - 2024. All rights reserved.