Home > OS >  Connecting to a remote MySQL database from Stackblitz Node.js project
Connecting to a remote MySQL database from Stackblitz Node.js project

Time:02-01

I have a Node.js Stackblitz project that I am trying to connect to a remote MySQL database. It is not possible to have a MySQL database within Stackblitz, hence trying the remote approach. However I get "Error: connect ETIMEDOUT" whenever I attempt a connection. Any help or pointers much appreciated.

I am using the code below. The remote database is accessible with the credentials I am using and returning data when used outside of Stackblitz. Is remote database access not possible with Stackblitz or am I missing something?

const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
const port = 3010;
const path = require('path');

app.use(express.static('static'));

app.get('/', async function (req, res) {
  try {
    // create connection
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      database: process.env.DB_DATABASE,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
    });

    // query database
    const [rows, fields] = await connection.execute('SELECT * FROM `user`');

    res.send({
      rows,
      fields,
    });

  } catch (err) {
    console.log('err:', err);
  }
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

CodePudding user response:

For anyone looking for an explanation.

Currently a mysql database cannot reside in StackBlitz. Additionally, neither can it connect to an external mysql database on its own either.

You therefore required a backend API outside of StackBlitz to make the database calls, negating the reason for building the backend on StackBlitz in the first place (IMO). Therefore, the suggested setup currently would be a localhost backend API accessed from a frontend in StackBlitz via an ngrok secure address.

StackBlitz are working on getting basic server requests running in the future. So, watch this space.

I hope this answer helps save others time.

  • Related