Unable to receive information from my mySQL database despite having seen tutorials doing the exact same thing
P粉757640504
P粉757640504 2024-04-03 14:46:04
0
1
316

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粉757640504
P粉757640504

reply all(1)
P粉204136428

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!');
        }
    })
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!