How to send JSON data instead of logging it to the console

Viewed 470

I'm working on a food ordering app in flutter and the API in Express.js with MySql for the database. I was able to connect to the database and receive the JSON data and console.log() them, but I don't know how to send them to the app. Any help would be highly appreciated.

Here's the code.

const express = require('express');
const router = express.Router();
const mysql = require('mysql');

var pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'ala_ainy_db',
    connectionLimit: 10,
});

router.get('/', (req, res, next) => {

    pool.getConnection(function (err, conn) {
        if (err) return;
        conn.query('SELECT * FROM restaurants', function (err, rows) {
            if (err) {
                conn.release();
                console.log('failed');
            }
            rows.forEach((row) => {
                console.log(`ID: ${row.id}, Name: ${row.name}`);
            });
            conn.release();
        })
    });
});
1 Answers

You could send your data in response with express res.json() or res.send() methods.

res.json() Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

res.send() Sends the HTTP response. The body parameter can be a Buffer object, a String, an object, or an Array.

Example:

const express = require('express');
const router = express.Router();
const mysql = require('mysql');

var pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'ala_ainy_db',
    connectionLimit: 10,
});

router.get('/', (req, res, next) => {

    pool.getConnection(function (err, conn) {
        if (err) return;
        conn.query('SELECT * FROM restaurants', function (err, rows) {
            if (err) {
                conn.release();
                console.log('failed');
            }
            conn.release();
            res.status(200).json(rows);
            
        })
    });
});
Related