I encountered an issue while attempting to connect to my MySQL database using my Express API endpoint: error message "connect ECONNREFUSED 127.0

I am currently in the process of developing a web application for a bootcamp using Express and MySQL. I have set up a route to handle a GET request to an endpoint which is supposed to query my MySQL database table and retrieve all records. My intention is to display the results on the Chrome page, but unfortunately, I encountered the following error:

Error: connect ECONNREFUSED 127.0.0.1:8211
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14)
    --------------------
    at Protocol._enqueue (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at Protocol.handshake (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/protocol/Protocol.js:51:23)
    at Connection.connect (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:119:18)
    at Connection._implyConnect (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:457:10)
    at Connection.query (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:199:8)
    at Object.getAllUsers (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/database/index.js:17:14)
    at /Users/cnebs/Documents/HRATX/hratx42-fullstack-review/server/index.js:22:6
    at Layer.handle [as handle_request] (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/route.js:112:3) {
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8211,
  fatal: true
}

Although I am able to successfully execute queries from the terminal to the database and display text on the Chrome page via Express, I am facing the issue mentioned above when attempting to retrieve data through the API.

Displayed below is the database index file:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "password",
  database: "github",
  port: 8211
});

const test = () => {
  connection.query("DESCRIBE git_repos", (err, res) => {
    console.log('selection: ', res)
  })
}

const getAllUsers = cb => {
  connection.query(`select * from todos`, (err, res) => {
    if (err) {
      console.log("error in getAllUsers: ", err);
      cb(err);
    } else {
      cb(null, res);
    }
  });
}

module.exports = { test, getAllUsers }

Provided below is the server index file:

const express = require('express');
const db = require('../database')
let app = express();


app.use(express.static(__dirname + '/../client/dist'));

app.get('/repos', function (req, res) {
  // TODO - your code here!
  // This route should send back the top 25 repos

  db.getAllUsers((err, result) => {
    if (err) {
      console.error(err)
      res.status(404).end();
    } else {
      console.log('Getting')
      res.send(result)
    }
  })
});

let port = 1128;

app.listen(port, function() {
  console.log(`listening on port ${port}`);
});

I was expecting to receive any output from my query on the page through the res.send method, however, instead, I face difficulties as the localhost page cannot be found and the error response appears in my server terminal.

Answer №1

When using createConnection(), you do not have the ability to manually select the port for your database server. Simply eliminate the port property and the function will work as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the distinction between assigning a value and setting text through JSE in Selenium using C#

Utilizing the IJavaScriptExecutor to set the attribute value can sometimes result in the text box containing the set value, but not displaying it as text. In some cases, the input is sent normally to certain text boxes, while for others, it is only setting ...

Problems with running Sequelize transactions within ExpressJS

Seeking guidance on utilizing Sequelize transactions in an expressjs environment. I have a specific code snippet that is meant to find a post by id, increase the reply count in the post table, update the post, and finally create a reply in the reply tabl ...

Ever since updating my jQuery version to 3.2.1, my ajax code seems to have stopped functioning properly

My program's ajax functionality was running smoothly with jquery version 1.7, but when I updated to version 3.3.1, the ajax part stopped working. I made sure to attach the ajax portion of my code after updating the jQuery version. In the PHP file, I s ...

Is there a way to trigger a confirmation function for form submission exclusively when clicking one specific submit button, and not the other?

Here is the layout of my form: <form action="newsletter.php" name="newsletter" id="newsletter" method="post"> <input type="submit" value="Submit" class="c-btn" id="submit_value" name="submit_value"> <input type="submit" value="Send" cla ...

Issue with ExpressJS Regex not correctly matching a path

I'm currently struggling with a simple regex that is supposed to match words consisting of letters (0-5) only, but for some reason it's not working as expected. Can anyone help me figure out the correct expression and how to implement it in Expre ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...

Is the for loop in Node.js completed when making a MySQL call?

A certain function passes an array named res that contains user data in the following format: [ RowDataPacket { UserID: 26 }, RowDataPacker { UserID: 4 } ] The goal is to create a function that fetches each user's username based on their ID and stor ...

Should the button be eliminated in favor of simply requesting input from the user?

Looking for help with my code. How can I set it up so that when the HTML file is clicked on, it prompts for input instead of displaying a button? I'm new to coding and could use some guidance. <!doctype html> <html> <head> <meta ...

Token does not function properly on Fetch request sent to PHP script

I have a pair of files: one is revealing a session token, while the other is responding to a javascript fetch. The first file goes like this: <?php session_start(); unset($_SESSION['sessionToken']); $_SESSION['sessionToken'] = vsprin ...

Finding distinct outcomes from an already screened roster using AngularJS

I have an array containing objects structured like this: { "date":"11/11/2014", "time":"17.20.37", "car":"396", "driver":"Jenny", "from":"Old Office", "destination":"Log WH", "pax":"3","comment":"", "commenttime":"", "arrival":"17.20.48", "inserted":true, ...

Can you explain which variable is considered global in Node.js?

Instead of writing var global = window for the browser I want my code to be able to work in a node environment as well. Something like var global = window || node_global What is node_global? I couldn't find any clear answer here: or here https ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

I am experiencing an issue where the button in express is not functioning as expected, and I am not

Currently, I am diving into learning express node.js. I've been working on a simple calculator code, but whenever I press the button, I do not receive any response back. Strangely, there are no errors showing up in my code either. I seem to be at a lo ...

The functionality of Dnd-kit nested is functioning properly, however, one specific component is unfortunately

Currently, I am dealing with a two-dimensional array that results in two nested dnd-kit drag and drop fields. The nested dnd functions correctly; however, the first one sorts items when moved without any animations (even when moving my div). Below is the ...

The never-ending cycle and memory overload that occur when using Angular's ngRoute

It seems like I may have hit a roadblock while attempting to get ng-view and ngRoute up and running. Everything appeared to be functioning correctly, but it looks like the entire process is caught in a loop. Just to provide some context, I am working with ...

Is it possible to utilize lambda:invoke to trigger an AWS Lambda express application?

Looking for a solution for my AWS Lambda express app that has multiple endpoints. Is there a way to bypass api-gateway and invoke the app directly using lambda:invoke? I'm struggling to find out how to access specific endpoints. Any suggestions or g ...

What is the reason behind Selenium not utilizing JavaScript?

I've been a beginner in the world of Javascript for a while now, with my main goal being to use it for creating Selenium automations as part of my journey into QA automation. However, I find myself quite perplexed when it comes to the language. In al ...

Error message "Truffle 'Migrations' - cb is not a valid function"

I created a straightforward smart contract using Solidity 0.6.6 and now I'm attempting to deploy it on the BSC Testnet. Here's what my truffle-config.js file looks like (privateKeys is an array with one entry ['0x + privatekey']): netw ...

What is the best way to access data stored in the state of the store.js within a Vue application?

Currently, I am working on my initial project using Vue.js. The application involves a multi-step form that shares a common header and footer. As the user progresses through each step, the data entered is sent to store.js for storage. However, I have encou ...