简体   繁体   中英

How to Return SQL FIeld Names in Javascript call to API?

I put together an API for a local mysql database with Express, Cors and Node and now am trying to pull data. I have one query where I have built a const meant to pull a series of stats, but I can't figure out how best to pull the data so that each element in the json has the correct field:

const express = require('express');
const cors = require('cors');
const mysql = require('mysql');

const app = express();

const COUNTS_QUERY = 'SELECT COUNT(*) AS total_stands FROM carts UNION SELECT SUM(current_orders) as total_orders FROM carts UNION SELECT AVG(rating) as rating FROM carts';

app.listen(4000, () => {
    console.log('Server listening on port 4000')
});

//call query to count trucks
app.get('/stats', (req, res) => {
    connection.query(COUNTS_QUERY, (err, results) => {
        if(err) {
            return res.send(err)
        } else {
            console.log(results)
            return res.json({
                data: results
            })
        }
    })
})

I receive the following result:

{"data":[{"total_stands":1541},{"total_stands":35218},{"total_stands":2.9792}]}

How can I get back an object where each stat has the appropriate field name?

Use this query in order to receive this output: {"data":[{"total_stands":1541},{"total_orders":35218},{"rating":2.9792}]}

SELECT
    (SELECT COUNT(*) AS total_stands FROM carts) AS  total_stands,
    (SELECT SUM(current_orders) as total_orders FROM carts) AS total_orders,
    (SELECT AVG(rating) as rating FROM carts) AS rating

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM