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

Received TypeError: Unable to call reset function - issue clearing input field post ajax request

Having Trouble Clearing Input Fields After AJAX Request: $.ajax({ type: "POST", url: "river_flow.php", data: { username: $("#username").val(), idv:$("#idv").val(), comment: $("#comment").val()}, cache: false, success: function(da ...

AngularJS - Determine the correct condition or make a choice from the available options

I'm having trouble figuring out how to save the option I select to a viewmodel. The ng-model should save whatever option I choose, and if nothing is selected, the value should default to "Select One." The available options are YES (true) / NO (false). ...

When attempting to render 2 components based on the results of 2 fetch calls using Promise.allSettled(), I encounter difficulties if one of them throws an error

I have encountered an issue while using Promise.allSettled() in sending two fetch calls. I am rendering components based on the result - a component with data if it is fulfilled and an error component if rejected. However, when one of the fetch calls throw ...

What could be causing the TypeScript error that pops up when I try to access req.files.length?

I am utilizing multer and encountering an issue while trying to access req.files. The specific typescript error I received is as follows: Operator '<' cannot be applied to types 'number' and 'number | File[]' This error oc ...

Call a PHP function within a functions file using a JavaScript function

Seeking a way to navigate between PHP and JavaScript worlds with confidence. There's a collection of PHP functions stored neatly in custom_functions.php waiting to be called from JavaScript. As I delve into the realm of JavaScript and jQuery, my fam ...

Troubleshooting: Angular Custom Elements malfunction on Firefox, Microsoft Edge, and Internet Explorer

Experimented with the Angular Elements Demo After downloading, installing, and building the demo locally. Implemented the following code: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Angular Eleme ...

Adding a dynamic form to each row in a table: A step-by-step guide

Hey there! I'm facing a challenge with dynamically generated rows in a form. I want to send only the inputs from the selected row when a checkbox is clicked. Can you help me figure this out? I tried using let rowForm = $(event.currentTarget).closest( ...

Guide to Making GraphQL API Calls from a Node.js/Express Server

After successfully implementing a schema and resolvers for my Express server, I tested them through /graphql. Now, I am looking to utilize the queries from a REST API by calling them in GET handlers like this: //[...] //schema and root are properly implem ...

Best method for converting MySQL array into a unified object

When querying the database, I always receive a result set as an Array with one object inside it. Since I control the queries, there will always be just one object. I have chosen not to use any ORM (like those listed [here](https://medium.freecodecamp.org/ ...

Intensive analysis of objects comparing their characteristics

Currently delving into the world of Javascript, I encountered a coding exercise involving a "deepEqual" function that I attempted to write but ultimately struggled with. Even after reviewing the solution, one particular part perplexed me - the for loop, ...

Tips for maximizing page layout efficiency without compromising on element visibility

What is occurring https://i.stack.imgur.com/Agjw6.gif The use of .hide() and .fadeIn(200) is resulting in a jittery effect that I would like to avoid. Desired Outcome When the user hovers over the menu icon, the menu icon should vanish the text "Pr ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

Unintentional GET request triggered by Axios baseURL

I have encountered a strange issue where defining axios.defaults.baseURL = baseUrl; results in an unexpected GET request right after initializing my Vue app. Any assistance would be greatly appreciated! Below are images showing the code and network reques ...

Executing Figwheel alongside Express.JS

When I run lein figwheel, it initiates a simple static hosting server through Ring on port 3449. This setup works fine for me. However, the issue arises when I have my own files hosted via node.js on port 3000. After running figwheel and starting my expre ...

Troubleshooting issues with applying styles in Vue framework when configured with webpack

I'm facing an issue with setting up the Vue framework using webpack. Specifically, I'm having trouble with styles not being applied when included in the <style> tag within single file components. Despite following several tutorials on this ...

AngularJS: accessing siblings by using the ng-click directive

I am currently working on a list (<ul>), which is being used in multiple instances within different ng-repeat iterations on the same page. The initial list items are generated through ng-repeat, with the second to last item containing a span. When this ...

Tips for extracting the index of the chosen item from a dropdown using ReactJs and Material UI

This is the code snippet for Dropdown component implementation: <DropDownField name={formElement.name} label={formElement.name} value={formik.values[formElement.name] || ''} dropDownItems={formElement.name === &apo ...

Every time I attempt to reuse my components, they keep piling up on top of each other

I'm facing an issue where I need to reuse components I've created multiple times while rendering dynamic content. However, when I attempt to render them, they end up stacking on top of each other in the same position. Each time I render ...

Tips for incorporating JavaScript into elements that have been modified using jQuery's .html() method

Consider this example: $('#key').on('click', function(){ $('.task').html("<button id='key'>Button</button>"+Date()); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.j ...

Obtain the correct form ID format that is dynamically loaded following the execution of an AJAX function

When adding dynamic HTML elements, it is recommended to use delegation binding. However, I am encountering an issue with getting the proper "id" of the form element. $(document).on("submit", "form#add_education", function(e){ e.preventDefault(); ...