What's wrong with this React connection to MySQL?
I am trying to connect to a database from my React app (which has routes). This get request using Express and MySQL was successful:
db/index.js
import mysql from 'mysql'
let pool = mysql.createPool({
connectionLimit: 10,
password: 'app',
user: 'app',
database: 'chirprapp',
host: 'localhost',
port: '3306'
});
let chirprdb = {};
chirprdb.all = () => {
return new Promise((resolve, reject) => {
pool.query('SELECT * FROM chirps', (err, results) => {
if (err) {
connection.end()
return reject(err);
}
return resolve(results);
})
})
}
chirprdb.one = (id) => {
return new Promise((resolve, reject) => {
pool.query('SELECT * FROM chirps WHERE id = ?', [id], (err, results) => {
if (err) {
return reject(err);
}
return resolve(results[0]);
})
})
}
route
import { Router } from 'express';
import db from '../db'
router.get('/:id?', async (req, res) => {
let id = req.params.id;
if (id) {
try {
let results = await db.one(id);
res.json(results);
} catch (e) {
console.log(e);
res.sendStatus(500);
}
} else {
try {
let results = await db.all();
res.json(results);
} catch (e) {
console.log(e);
res.sendStatus(500);
}
}
});
But when I try to make a simpler get request like
db/index.js
let mysql = require('mysql')
let connection = mysql.createConnection(
{
host: 'localhost',
database: 'chirpapp',
user: 'app',
pasword: 'app'
}
);
module.exports = connection;
route
import { Router } from 'express';
import connection from '../db'
let router = Router();
router.get('/', (req, res) => {
connection.connect()
connection.query('SELECT * FROM chirps', (err, results) => {
if(err) {
connection.end();
res.sendStatus(500);
return console.log(err);
}
res.json(results);
return connection.end();
})
})
I get a status 500 internal service error and SyntaxError: Unexpected token I in JSON at position 0. From what I've read online, the syntax error means the server is sending back HTML instead of JSON.
Why would I get two different responses for basically the same request?
This is the first time I've done this, so any insight from you is guaranteed to shed some light.