Unable to retrieve data from MySQL Database using Express Route

Struggling to understand how to execute a MySQL database query within the promise in my route file. Currently, I am developing a RESTful API for interacting with a MySQL database using GET methods. The technologies being utilized are Express for the backend and Axios for handling Javascript promises. My goal is to retrieve the list of books from a specific SQL table along with the count of listings present in the returned JSON.

server.js

const http = require('http');
const app = require('./app');

const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);

app.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');

const bookRoutes = require('./api/routes/books');
const entryRoutes = require('./api/routes/entries');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'rlreader',
    password: process.env.MYSQL_DB_PW,
    database: 'books'
});

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'GET');
        return res.status(200).json({});
    }
    next();
});

// Routes for handling requests
app.use('/books', bookRoutes);
app.use('/entries', entryRoutes);

app.use((req, res, next) => { 
    const error = new Error('Not found');
    error.status = 404;
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    });
});

module.exports = app;

books.js

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

router.get('/', (req, res, next) => {
    axios.get('/').then(docs => {
        res.status(200).json({
            "hello": "hi" //Intending to perform a MySQL database query here
        })
    }).catch(err => {
        res.status(500).json({
            error: err
        });
    })
});

module.exports = router;

Seeking advice on how to pass the const connection object from app.js to books.js?

Answer №1

I made an update by moving the code that connects to the MySQL database into a separate file and then included it:

const connection = require('../../db');

Following that, I ensured the response was properly returned:

router.get('/', (req, res, next) => {
    let responseData = axios.get('/').then(docs => {
        const sqlQuery = "SELECT title, id FROM books";
        connection.query(sqlQuery, function (err, result) {
            if (err) {
                console.log("An error occurred");
            }
            return res.status(200).json(result);
        });
    }).catch(err => {
        res.status(500).json({
            error: err
        });
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to add a personalized parameter to an unnamed JavaScript replace function?

I am looking to customize a date value in the following format: var d = new Date(); myobj.format(d, "dddd (ddd) S dd'd'.MM (MMM MMMM).yyyy HH:mm:ss.fff t tt T TT (o) {Z}"); I prefer not to utilize date.js because of its large size. The issue ...

AngularJS $http get isn't functioning properly, but surprisingly $.ajax works perfectly

Recently delving into the world of AngularJS, I am facing a hurdle with $http functionality. In my factory setup below: app.factory('employeeFactory', function ($http) { var factory = {}; // Retrieving data from controller var emplo ...

Dynamic water filling effect with SVG

I'm trying to create a wipe animation that looks like water filling up inside of a drop shape. Currently, it is a square with a wave animation on top of the drop logo. The wave animation works correctly, but I am struggling to contain it within the dr ...

The process of masking a video with alpha data from another video on canvas seems to be experiencing a

I have a unique setup on my page where I'm masking one video with another. Essentially, when the Play button is pressed, a second video slowly appears over the looping video in the background. This effect is achieved by using a black/white mask transf ...

Acquire the URL using Angular within a local environment

I am currently working on a basic Angular project where I have a JSON file containing some data. [{ "name": "Little Collins", "area": "Bronx", "city": "New York", "coverImage": "https://images.unsplash.com/photo-1576808597967-93bd9aaa6bae?ixlib=rb-1.2.1&a ...

Are there any publicly accessible APIs available to retrieve data values based on the file type?

Currently, I am working on a project that requires uploading and downloading files. The current functionality allows only .csv and .txt file types to be downloaded using the code snippet below: downloadFile(file).then( function (response) { va ...

Utilize Moment.js in AngularJS for formatting dates

I have been attempting to use moment.js in Angularjs to format a date, but it seems like I am running into some issues. Here is the link to my code snippet on jsfiddle http://jsfiddle.net/sed6x5e8/ and below you can find the HTML and JS code that I am work ...

Ways to access and delete the canvas using ref steps?

Having a canvas in a react component, I utilized react refs to access the node and implemented a destroy() method. However, I encountered an error: TypeError: canvasRef.current.destroy is not a function How can we properly access the node (canvas) using r ...

Guide on executing MySQL queries in AngularJS with the help of the Laravel 4 framework

I am having issues executing MySql Queries in the Laravel framework using AngularJS. I am currently unable to successfully delete a database record through the button functionality. The existing code is able to insert data into the database, retrieve data ...

Expanding functionality: Steps to integrating a new endpoint into your AWS Amplify Express Server

I have created a REST express server using Amplify. Attempted to include two additional endpoints: // incorporating serverless express app.post('/myendpoint', function(req, res) { console.log('body: ', req.body) res.json(req.body) ...

PhantomJS Karma encountering SyntaxError when trying to export variables

I've encountered an issue while running Karma and PhantomJS. When I attempt to run, the console displays the following message: 22 03 2016 14:58:47.865:WARN [karma]: No captured browser, open http://localhost:9876/ 22 03 2016 14:58:47.875:INFO [karm ...

Tips for sending custom props to a dynamic page in Next.js

I have created a component called Card.js which is responsible for linking to dynamic pages when a card is clicked. My goal is to pass a value, such as 'category', to the dynamic page [id].js so that I can implement additional logic there. Card. ...

Ensuring Type Safety in Typescript

I have a specific requirement where I need to validate the structure of a request body to ensure it conforms to a predefined type. Is there a way or a package that can help achieve this validation? type SampleRequestBody = { id: string; name: string; ...

Assign a class to the element only when the second div also has a class

I am trying to create a functionality where I have a dropdown element (Li element) that receives an Active class when its parent div (button) is clicked. When the dropdown element has this class, I want to assign the same class to another div. If the dropd ...

Retrieving over 300,000 rows from elasticsearch and saving them as a .csv document

Hi there, I am currently working on a website in nodejs that utilizes an Elasticsearch database. One of my indexes, 'bigData*', contains 366,844 rows with each row consisting of 25 items, each being a different string of varying sizes (with a max ...

The sign-up button mysteriously vanishes after the page is refreshed

I am encountering an issue with the sign up button during the user registration process. There is a checkbox for Terms & Conditions, and the button should only become enabled after checking this box. Everything seems to be functioning correctly, but when I ...

Vercel Next JS features server and client components with distinct timezones

In my Next.js 13.2.4 project, there is a useful helper function named getLocalTime(date) that retrieves the local time of the user's machine in a specific format. //Desired output: 9:30PM export function getLocalTime(date) { const localTime = new D ...

What are the steps to implement session storage within a Puppeteer automation script?

Currently, I am attempting to retrieve the encounter id from a Puppeteer script that launches a browser. These scripts are executed on AWS synthetic canaries. However, when running the script, I encounter the following error: sessionStorage is not define ...

live PHP recording of data moving between tables

As a beginner, I am working on a project to organize groups of people on the screen using PHP code. I have managed to list Distribution Lists, Member Lists, and People, but I lack experience in this area. Can anyone provide some guidance on how to proceed? ...

Verify whether the cookie information is in an array format

As visitors click on products on my site, I am storing their IDs in a cookie. Each click adds the new ID to an array stored in the cookie. This is how I set up the cookie and its current value after a few clicks: var cookieArray = []; cookieArray.push( ...