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

Error message in Angular states that it is not possible to bind to 'formGroup' because it is not recognized as a property of 'form' within Angular

When trying to extract data from a form using formcontrol, everything seems to be working fine except for the [formcontrol] = "userForm" in the HTML. If I remove this part, the project runs smoothly. I have tried multiple tutorials but none of them seem ...

Unfortunately, an exception was encountered: ES Module must be loaded using the import statement

Currently, I am addressing some vulnerability concerns within my Angular development environment. These vulnerabilities are found within internal dependencies, so I have included resolutions in the package.json file. However, when I attempt to run 'ng ...

Activate fullscreen mode in Videogular by using the `toggleFullscreen()` function

I've been trying to switch to fullscreen using the videogular API, but I'm having trouble getting it to work. Oddly enough, while that.API.play() functions correctly, that.API.toggleFullscreen() does not. I've looked into the vg-controls pl ...

Tips for executing the JetBrains WebStorm refactoring tool 'modify ES6 import' for an entire project

Following a project refactor, certain files were relocated to a different npm package, leading to changes in source files to re-export them from their new location (in order to streamline the migration process). Later on, I came across a helpful refactori ...

Is it possible to automatically submit a form at regular intervals without reloading the page and simultaneously insert the submitted data into

I am attempting to automatically submit a form every x number of seconds without refreshing the page and then insert the input data into a MYSQL database. The problem I'm facing is that while I can successfully insert the form's input value into ...

What is the local date format for the Ionic DatePicker?

I have successfully implemented a DatePicker in my Ionic Project, but the date is displaying in the wrong time format. Here is my function: showDatePicker(){ this.datePicker.show({ date: new Date(), mode: 'date', allowOldDates: fal ...

Tracking the number of queries executed during each page load using PDO

I am interested in finding a way to enhance the PDO object by adding an internal counter each time a query is executed. I want to accomplish this without having to modify any of my existing queries or incorporating an additional function like the suggestio ...

Best Practices for Displaying Videos in Ionic 2

Can videos be properly integrated into Ionic pages? I'm encountering an issue where the buttons become unusable in fullscreen mode when using the html 5 video element. <video id="video1" width="100%" preload="metadata" controls webkit-playsinline& ...

Runtime error: Hibernate reports a "Table not found" issue

After successfully creating a database with no errors and adding dummy data, I encountered an error when trying to retrieve data from the database. The console showed an attempt to recreate a table that had already been created. I searched online but could ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

Setting up a Mean Stack on AWS Lightsail

I am currently experimenting with AWS Lightsail and struggling to grasp how to set it up properly. I have successfully created a Bitnami MEAN instance. On my local machine, I have Angular 6 running via CLI and a NODE API backend on two different ports: 42 ...

Using Angular 6 HttpClient to retrieve an object of a specific class

Previously, we were able to validate objects returned from http api calls using the instanceof keyword in Angular. However, with the introduction of the new HttpClient Module, this method no longer works. I have tried various simple methods, but the type c ...

Querying the left substring in mysql can be achieved by using the SUB

It may seem unusual, but I'm struggling to find a simple solution for my task: I have multiple rows containing various absolute paths such as: /application/themes/openbank/images/prettyPhoto/light_square/default_thumbnail.gif /application/themes/op ...

Leveraging angular-cli to compile a library that can be easily integrated into multiple projects

Let me provide some context: I set up an angular-cli (beta 17) project for my organization that includes multiple components I want to share with other Angular 2 projects within the organization. Initially, I kept it simple by using npm to install the Gi ...

Tips for selecting the best className type for material-ui components

Currently, I am integrating material-ui into a react app that is built using typescript. Within the material-ui framework, there is a feature called withStyles which allows styles to be injected into a component through its className. However, I am facing ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

The PHP AJAX comment system is malfunctioning as the query fails to insert any data

Having an issue with my comment system. I'm using the code below, but when I enter a comment and name then click on submit, nothing happens - no errors or warnings, it just doesn't insert anything. Can someone help me identify what's wrong w ...

You are unable to apply 'use client' on a layout element in Next.js

While attempting to retrieve the current page from the layout.txt file, I encountered errors after adding 'use client' at the top of the page: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data parseMod ...

Is there a way to retrieve a JSON request through a webview in Android Studio?

Hello, I am facing an issue while trying to retrieve a JsonRequest from a submit on a Webview. I have tried various codes but none seem to work for me as I don't have much experience in this area. Even though this question has been asked before, I sti ...

What is the solution for this problem in TypeScript involving an API service call?

Trying to utilize the API Service to fetch data and display the response as an object created by a class constructor Currently executing a Typescript code that interacts with the API Service import * as request from "request"; import { Users } from "./Us ...