James Gordon
James Gordon

Reputation: 21

How to get the response JSON from API call

I want to retrieve the JSON response from the api call I am doing. Example, I want to retrieve something like this:

{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}

This is my API call using fetch in react. (yes I know sending password in URL is bad, it's for a school project)

        fetch('/api/user/'+ user + '?password=' + password, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }}).then((res) => {
                console.log(res); //I want to get the JSON stuff here
              })

This is the API call I am calling.

app.get('/api/user/:user', function (req, res) {
    // console.log(JSON.stringify(req));
    // var user = req.body.user;
    // var password = req.body.password;

    var user = req.params.user;
    var password = req.query.password;

    console.log(user, password);

    var result = { error: {} , success:false};
    if(user==""){
        result["error"]["user"]="user not supplied";
    }
    if(password==""){
        result["error"]["password"]="password not supplied";
    }
    if(isEmptyObject(result["error"])){
        let sql = 'SELECT * FROM user WHERE user=? and password=?;';
        db.get(sql, [user, password], function (err, row){
            if (err) {
                res.status(500); 
                    result["error"]["db"] = err.message;
            } else if (row) {
                res.status(200);
                result.data = row;
                result.success = true;
            } else {
                res.status(401);
                result.success = false;
                    result["error"]["login"] = "login failed";
            }
            res.json(result);
        });
    } else {
        res.status(400);
        res.json(result);
    }
});

When I do console.log(res) in the fetch call, this is what is printed:

Response {type: "basic", url: "http://localhost:3000/api/user/tim?password=123", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "basic"url: "http://localhost:3000/api/user/tim?password=123"proto: Response

When I visit the website, the output is:

{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}

This is what I want.

Upvotes: 0

Views: 3399

Answers (4)

Najla
Najla

Reputation: 1

try this

fetch(${baseUrl}/api/user/${user}?password=${password},{
        method:'GET', 
        headers: {
        'Accept': 'application/json',
        'Content-Type': 
        'application/json',
        }}) .then(async(response ) => { 
             await response.json()
             })

Upvotes: 0

Gelo
Gelo

Reputation: 1

for you to get the JSON body content from the response, you need to use json()

fetch('/api/user/'+ user + '?password=' + password, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }}).then((res) => {
                const jsonData = res.json();
                console.log(jsonData);
              })

Upvotes: 0

wentjun
wentjun

Reputation: 42526

In general, this is how you return the response body from the Promise.

fetch(`${baseUrl}/api/user/${user}?password=${password}`, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }})
  .then(response => response.json())
  .then‌​(data=> { 
    console.log(data); 
  })

Upvotes: 1

Arfeo
Arfeo

Reputation: 867

Try this way to parse the response:

fetch('/api/user/'+ user + '?password=' + password, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }}).then(async (res) => {
    const raw = await res.text();
    const parsed = raw ? JSON.parse(raw) : { success: res.ok };

    console.log(parsed);
  })

In this case you can also add some checks for response statuses (if you want, of course) along with parsing the result JSON.

Upvotes: 0

Related Questions