Establishing a connection between MySQL database and an Ionic/Angular application

I have been working on an Ionic/Angular project and I'm facing difficulties in establishing a connection with my MySQL database (mariadb). Despite trying various solutions from online sources, I keep encountering numerous error messages. Any guidance on the most effective method to connect my MySQL database to my Ionic/Angular application would be highly appreciated.

Let's consider that my database is located on server 11.11.111.111, named 'products', with a table called 'items'. My login credentials are username: hain and password: 1234.

In order to address this issue, I've created a page for connection.service:

import { Injectable } from '@angular/core';
import { createPool, Pool } from 'mariadb';

@Injectable({
  providedIn: 'root'
})
export class ConnectionService {
  private pool: Pool = createPool({
    host: '11.11.111.111',
    user: 'hain',
    password: '1234',
    database: 'products',
    connectionLimit: 5
  });

  constructor() { }

  getItems(): Promise<any> {
    return this.pool.getConnection()
      .then(conn => {
        return conn.query("SELECT * FROM items")
          .then(rows => {
            conn.release();
            return rows;
          })
          .catch(err => {
            conn.release();
            throw err;
          })
      })
      .catch(err => {
        throw err;
      });
  }
}

Additionally, I have a tab2 page:

import { Component, OnInit } from '@angular/core';
import { ConnectionService } from '../services/connection.service';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
 export class Tab2Page implements OnInit {

  product: any;

  constructor(private connectionService: ConnectionService) {}

  ngOnInit() {
    this.ConnectionService.getItems().then((data) => {
      this.product = data;
    }).catch((err) => {
      console.log(err);
    });
  }

}

The following type of errors are being displayed:

    ./node_modules/mariadb/lib/cmd/handshake/auth/caching-sha2-password-auth.js:2:11-24 - Error: Module not found: Error: Can't resolve 'fs' in …
[ng]
[ng] ./node_modules/mariadb/lib/cmd/handshake/auth/ed25519-password-auth.js:4:15-32 - Error: Module not found: Error: Can't resolve 'crypto' in …

I attempted resolving this by adding details to package.json:

 "browser": {
    "fs": false,
    "net": false,
    "tls": false,
    "os": false,
    "zlib": false,
    "crypto": false
  }

Despite researching extensively, configuring webpack.config.js did not yield successful results. If you have a more efficient or secure approach for handling a mariadb database, I am open to exploring all suggestions.

Answer №1

One common mistake made by many new developers is trying to connect directly to their database from the front end. This poses a significant security risk and should never be attempted, regardless of the project.

The proper way to handle your database connection is on the back-end (server-side). The front-end (client-side) should send a request to the server asking for data from the DB, and the server should respond with the requested information. This approach is the most secure method.

For those who are new to this concept, it's important to understand why this practice is crucial. Your connection details, such as host, user, and password, should remain confidential and accessible only to authorized website administrators. Exposing this sensitive information on the front-end allows anyone to access and potentially compromise your database, putting your data at risk.

Furthermore, it's essential to recognize that all front-end code on a website can be easily viewed, downloaded, and copied by users. Simply by right-clicking the page and selecting "Inspect," one can access the source tab and view all the code present.


In regards to any errors, it's challenging to pinpoint the issue without more context. Double-check that you have correctly placed your browser element in the appropriate file at the root level. If not, that may be contributing to the problem.


Additionally, I noticed a typo in your ngOnInit function. It should read this.connectionService, not this.ConnectionService (note the capital C). If this hasn't been addressed yet, now would be a good time to make that adjustment.

I hope this information proves helpful.

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

What is the procedure for disabling validation in the onValueChanged function within Angular?

Is there a way to disable validation in the onValueChanged function in Angular? Check out this demo I have a form where I change the device value upon completion. However, every time I click on the device (in the onValueChanged function), it triggers the ...

Learn how to conceal every third digit entered into an input box. When the submit button is clicked, reveal the original unmasked values

Currently, I am looking to implement masking for digits as they are being typed, rather than just on blur. Additionally, I would like the original entered values to be displayed when the submit button is clicked. You can find my attempt at this here: https ...

An issue with the validation service has been identified, specifically concerning the default value of null in

Using Angular 10 and Password Validator Service static password(control: AbstractControl) { // {6,100} - Check if password is between 6 and 100 characters // (?=.*[0-9]) - Ensure at least one number is present in the strin ...

Is there a way to adjust the background color of the clicked tab with divs and revert the others back to their original color?

<span class="row top-bar-left align-items-center" style="width: 80%; float:left"> <div tabindex="1" class="link tab" routerLink="details" routerLinkActive="active" [qu ...

Mysql coding for search engines utilizing names

I am trying to create a search engine in PHP that searches for people using their first and last names, each stored in separate columns. Currently, I am using the following SQL query: SELECT * FROM users WHERE first_name OR last_name LIKE '$search_ ...

How can I dynamically replace a specific element inside a .map() function with a custom component when the state updates, without replacing all elements at once?

I'm currently developing a task management application and I need to enhance the user experience by implementing a feature that allows users to update specific tasks. When a user clicks on the update button for a particular task, it should replace tha ...

The import component functions correctly when it is located in the app folder, but does not work when it is installed as

I have a situation with an angular 2 component. When I place it in app-name/src/app/component-folder/component.ts and import it as import {Component} from './component-folder/component', everything works perfectly fine. However, if I install the ...

Strategies for extracting the type argument from a nested property and transforming it into a different value

I’m struggling to find the right way to frame my question, so I’ll provide an example of what I need help with. Let's assume I have the following object: const obj = { one: 'some string', two: new Set<string>(), }; Now, I wan ...

The data type 'Observable<any>' cannot be assigned to the type 'StoresSummaryResults'. The property 'Data' is not present in the 'Observable<any>' type

As a newcomer to using the Observable with Angular 2, I am facing an issue where my structure is not receiving the results despite being able to validate the response from my REST API. Below is the data class in Typescript that I have: import { RESTResul ...

The formatting directive fails to keep pace with speedy input

I am working on a feature to automatically format the input field as the user types, transforming the letters into valid initials in uppercase with dots in between. The formatting needs to happen in real-time as the user inputs characters, rather than aft ...

Experiencing Issues with MySQL Data Length?

I am currently working with the mysql2 library in conjunction with NodeJS. I have identical code and database structures on both my local machine and a server. Interestingly, when I attempt to upload an image into the "photos" table on my local setup, ever ...

Can you explain the significance of using an exclamation mark after defining a variable in TypeScript?

As I delve into TypeScript in an effort to enhance my programming skills, I have encountered the use of exclamation marks when defining variables. An example of this can be seen in the following code snippet: protected _db!: CheckpointDB ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

Execute a selector on child elements using cheerio

I am struggling to apply selectors to elements in cheerio (version 1.0.0-rc.3). Attempting to use find() results in an error. const xmlText = ` <table> <tr><td>Foo</td><td/></tr> <tr><td>1,2,3</td> ...

php retrieve and show data from MySQL database based on selection from dropdown menu

I've encountered an issue where I can retrieve data from a database and display it in a drop-down menu, but I'm not sure how to use the same drop-down list as input within a form. My code retrieves project names from the database and displays the ...

Creating a custom event handler for form input changes using React hooks

A unique React hook was created specifically for managing form elements. This hook provides access to the current state of form fields and a factory for generating change handlers. While it works seamlessly with text inputs, there is a need to modify the c ...

JEST: Troubleshooting why a test case within a function is not receiving input from the constructor

When writing test cases wrapped inside a class, I encountered an issue where the URL value was not being initialized due to dependencies in the beforeAll/beforeEach block. This resulted in the failure of the test case execution as the URL value was not acc ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...