Home  >  Q&A  >  body text

Unable to receive information from my mySQL database despite having seen tutorials doing the exact same thing

So I'm trying to make a program that reads and writes to a MySQL database, which led me to the YouTube tutorial. My problem is that despite going through the exact same process as the guy in the tutorial, I end up with an empty server despite what should be popping up. My code is as follows, it should grab every entry in the applicant_info table in my applicant database and display it on the browser at localhost:3000. Instead it shows nothing, I'm guessing it's because it can't get the information, but I don't know why this is happening, I've followed the tutorial exactly.

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

const connection = mysql.createConnection({
        host    : 'localhost',
        user    : 'root',
        password: 'password',
        database: 'applicants'
});

const app = express();

app.get('/', (req, res) => {
    let sql = "SELECT * FROM applicant_info";
    connection.query(sql, (err, results) =>{
        res.send(results);
    })
});

app.listen('3000', () => {
    console.log('Server running on port 3000');
    connection.connect((err) => {
        if(err) {
        };
        console.log('Database Connected!');
    })
});

A side note about the code is that for some reason I can't run it using the "throw" command, which is why the "err" if statement is currently empty. I hope dear God this isn't the cause because I don't know how to fix it.

This is the image I received from the browser: Image Description

P粉757640504P粉757640504179 days ago313

reply all(1)I'll reply

  • P粉204136428

    P粉2041364282024-04-04 10:50:52

    There is a problem with your request:

    Error: Cannot find module 'mySQL'

    should be:

    const mysql = require('mysql');

    So your server is not running and you are getting a 404 error on your browser.

    After repair, start your server,
    You should see this in the console:

    Server running on port 3000
    Database Connected!

    You should see your data when you visit http://localhost:3000

    edit:

    Added more debugging to your code:

    app.get('/', (req, res) => {
        console.log('get called');
        let sql = "SELECT * FROM applicant_info";
        connection.query(sql, (err, results) =>{
            res.send(results);
        })
    });
    
    app.listen('3000', () => {
        connection.connect((err) => {
            if(err) {
              console.log('Database not connected!');
              console.log(err)
            } else {
              console.log('Server running on port 3000');
              console.log('Database Connected!');
            }
        })
    });

    reply
    0
  • Cancelreply