expressjsHow do I connect an Express.js application to a MySQL database?
To connect an Express.js application to a MySQL database, you will need to install the mysql
module and use it to create a connection.
const mysql = require("mysql");
const connection = mysql.createConnection({
host: "localhost",
user: "me",
password: "secret",
database: "my_db"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Output example
Connected!
The code above does the following:
- Require the
mysql
module. - Create a connection to the MySQL database using the
createConnection()
method. - Connect to the database using the
connect()
method.
You can find more detailed information on connecting to a MySQL database with Express.js in the Node.js MySQL Documentation.
More of Expressjs
- How do I use Yarn to add Express.js to my project?
- How do I find Express.js tutorials on YouTube?
- How can I use the x-forwarded-for header in Express.js?
- How do I manage user roles in Express.js?
- How can I use express-zip js to zip and download files?
- How can I disable the X-Powered-By header in Express.js?
- How do I implement CSRF protection in an Express.js application?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js to make an XHR request?
- How can I use Express.js to develop a web application?
See more codes...