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 find Express.js tutorials on YouTube?
- How can I use Express.js and Keycloak together to secure an application?
- How do I implement CSRF protection in an Express.js application?
- How can I set up unit testing for an Express.js application?
- How can I set up X-Frame-Options in ExpressJS?
- How can I set up the folder structure for an Express.js project?
- How do I use Express.js and Yarn together in a software development project?
- How can I disable the X-Powered-By header in Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js to create a redirect?
See more codes...