0

So I want to build a website that queries data from a MySQL database. I installed the mysql package in Node.js (command: npm install mysql).

On my local machine it works but it doesn't in the browser which I understand because the package is only installed locally.

I now want to know how I can use this NPM package in a browser and still use the require() method for my database.

Code (if needed):

const mysql = require("mysql");

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "test"
});

connection.connect((err) => {
    if (err) {
        console.log("connection = false; error: " + err);
    } else {
        console.log("connection = true");
    }
});

connection.query("SELECT * FROM databasetest", (err, response) => {
    for (let i = 0; i < response.length; i++) {
        console.log(response[i]);
    }
});

Thanks!

corv1njano
  • 21
  • 2
  • Aside from `require`, I certainly wouldn't expect `mysql` to work in the browser. (And giving users *direct access* to the database is generally not a great idea.) Why do you specifically want to access the database from the browser instead of keeping that functionality server-side in Node? – David Jul 26 '23 at 15:30
  • Does this answer your question? [Browser: Uncaught ReferenceError: require is not defined](https://stackoverflow.com/questions/19059580/browser-uncaught-referenceerror-require-is-not-defined) – David Jul 26 '23 at 15:33
  • I don't know much about databases yet. My idea is a website that contains like a dictionary where users can look up words etc. I firstly planned to use the fetch() method and use a JSON file as my database but the JSON file would get too big after some time so I decided to use a database. I'm currently testing things with XAMPP's localhost features. – corv1njano Jul 26 '23 at 15:36
  • 1
    If you're new and don't know much about databases then you *definitely* don't want to completely expose your database to end users. Your server *will* be compromised. Think of the overall application functionality in two distinct pieces, server-side (in Node, likely using Express) and client-side (in the browser). The server would provide access to static resources (HTML, CSS, client-side JS, etc.) as well as API endpoints for any AJAX operations. The client would make API requests to interact with the server. Keep all database interactions server-side. – David Jul 26 '23 at 15:39

0 Answers0