0

i tested rest api using postman and the result

{
    "success": true,
    "message": "success",
    "data": [
        {
            "id_buku": 9,
            "judul_buku": "xxxxxx",
        }
    ]
}

I want "data" : {...} but the result is "data" : [{...}]

i am using express node.js to develop rest api

getDataBukuByID(req,res){
    let id = req.params.id;
    pool.getConnection(function(err, connection) {
        if (err) throw err;
        connection.query(
            `
            SELECT * FROM buku WHERE id_buku = ?;
            `
        , [id],
        function (error, results) {
            if(error) throw error;

            res.send({
                success: true,
                message: 'success',
                data: results
            });
        });
        connection.release();
    })
},

what code should be changed?

1
  • You can get the object from the array response.data[0] Commented Jun 16, 2021 at 4:18

2 Answers 2

1

hi bro actually what do you mean..? if you want value in an object you can use data.id_buku to get the value '9

Sign up to request clarification or add additional context in comments.

Comments

1
res.send({
    success: true,
    message: 'success',
    data: results
});

On the data key, you have assigned the variable named results which is returning by the callback function. As it is returning as an array of objects, so this is why the final output on that property is returning as array of object. The result must be always array of objects if it returns one more collection of data. Otherwise return single row to get an specific object as well.
You can use LIMIT on your mysql query to fetch single data. Then just return that row as an object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.