Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - fetch API, GET method return "ƒ json() { [native code] }"

I woud like to understand the difference between the two get methods, one work, the other not really but i don t understand why.

This doesn't work:

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);
    });

and return :

ƒ json() { [native code] }

This works well:

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);
});

and return:

{tasks: Array(4)} tasks : (4) [{…}, {…}, {…}, {…}] proto : Object

If you want to try it:

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);
    });
like image 828
artless boy Avatar asked Feb 13 '18 19:02

artless boy


2 Answers

It doesn't work because you are returning the res.json function. You have to call it and return a Promise:

.then(res => res.json())
like image 171
Derek 朕會功夫 Avatar answered Oct 10 '22 03:10

Derek 朕會功夫


.json is a function. you will have to call it. .then(res => res.json())

like image 27
Daniel A. White Avatar answered Oct 10 '22 01:10

Daniel A. White