简体   繁体   中英

Connecting to MySQL Database from React?

I've been having problems with connecting to a database. It is a remote database and no matter what I do, it just doesn't work. I've searched all around to no avail. I'm using React for doing so. I just want to make a simple connection and be able to run some queries: Here's the code:

db.js component:

const mysql = require('mysql');
const db = mysql.createConnection({
    /*THE VALUES BELOW ARE NOT THE ONES I HAVE TO USE*/
    host: '11.111.11.11', 
    user: 'username',
    password: 'password',
    port: 'port',
    database: 'database'
});

module.exports = db;

server.js in my backend folder:

const express = require('express');
const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;

app.use(cors());
app.use(express.json());

//ROUTE
app.get("/db", (req, res) => {
    db.query("SELECT * FROM users", (err, result) => {
        if(err) {
            console.log(err);
        } else {
            res.send(result);
            console.log(result);
            console.log('Connected!');
        }
    });
});

app.listen(PORT, ()=>{
    console.log(`Server is running on http://localhost/${PORT}/`);
});

I'm not getting anything from it, not even the logged info I asked for in the console.log()

Thanks for the help, in advance.

You have just created the connection, however you need also use the connect function to connect to your database. So you need to add a line in your server.js, (I have put a comment near the line that you missed to write.

const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;

app.use(cors());
app.use(express.json());

db.connect(); // you missed this line

//ROUTE
app.get("/db", (req, res) => {
    db.query("SELECT * FROM users", (err, result) => {
        if(err) {
            console.log(err);
        } else {
            res.send(result);
            console.log(result);
            console.log('Connected!');
        }
    });
});

app.listen(PORT, ()=>{
    console.log(`Server is running on http://localhost/${PORT}/`);
});

I think you can also do this in db.js before exporting db.

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