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
mysqlmodule. - 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 find Express.js tutorials on YouTube?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js to yield results?
- How do I use Express.js to parse YAML files?
- How can I set up X-Frame-Options in ExpressJS?
- How can I disable the X-Powered-By header in Express.js?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How do I download a zip file using Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js to prevent XSS attacks?
See more codes...