Here are the basic steps to create a Node.js Express backend CRUD (Create, Read, Update, Delete) application.
- Set up a Node.js project: Create a new folder for your project and initialize it with npm by running
npm init
in the command line. This will create apackage.json
file for your project. - Install Express: Install the Express framework by running
npm install express
in the command line. - Create an Express server: Create a new JavaScript file, let’s call it
server.js
, and require the Express module at the top of the file. Create a new instance of theexpress
class and set up the server’s basic configuration, such as the listening port.
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Here’s an example of how to create an Express server in server.js
In this example, we start by requiring the express
module and creating a new instance of the express
class. We also set the port
variable to 3000, which is the port number that our server will listen on.
Next, we call the listen()
method on our app
instance, passing in the port
variable and a callback function that will be executed when the server starts running. The callback function logs a message to the console to let us know that the server is running.
This is a very basic example, but you can add more configuration to your server as needed, such as middleware, error handling, or static file serving.
Create a router: Create a new JavaScript file, let’s call it router.js
, and require the Express module and create an instance of the Router
class. Define your application’s endpoints (i.e., routes) using the router’s methods, such as router.get()
, router.post()
, router.put()
, and router.delete()
.
const express = require('express');
const router = express.Router();
// Define your application's endpoints here
router.get('/', (req, res) => {
res.send('Hello, World!');
});
module.exports = router;
In this example, we start by requiring the express
module and creating a new instance of the Router
class. We then define an endpoint for a GET
request to the root URL ('/'
). When this endpoint is accessed, the server will send the response “Hello, World!” back to the client.
You can define as many endpoints as you need using the router’s methods, such as router.get()
, router.post()
, router.put()
, and router.delete()
. You can also define sub-routers to organize your endpoints into separate modules.
Finally, we export the router using module.exports
, so that it can be imported and used in our main server file (server.js
). To use the router module defined in router.js
in server.js
, you need to import it into server.js
using require()
. Here’s an example of how to do that:
const express = require('express');
const router = require('./router'); // Import the router module
const app = express();
const port = 3000;
app.use(router); // Tell the app to use the router
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
In this example, we start by requiring the express
module and importing the router module using require()
. Since the router module exports a Router
instance, we simply import it and assign it to the router
constant.
Next, we create a new instance of the express
class, set the port
variable, and tell the app to use the router by calling app.use()
and passing in the router
constant. This will make all the endpoints defined in the router available to the app.
Finally, we call the listen()
method on the app instance, just like we did in the previous example. When the server starts running, it will use the router to handle incoming requests.
Note that you’ll need to make sure that the path passed to require()
is correct and matches the file path of your router module. In this example, we assume that router.js
is located in the same directory as server.js
.
here’s an example of how to create an Express router for a CRUD application using MySQL
const express = require('express');
const router = express.Router();
const mysql = require('mysql');
// Set up a MySQL connection pool
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database'
});
// Define the CRUD endpoints
router.get('/users', (req, res) => {
pool.query('SELECT * FROM users', (error, results) => {
if (error) throw error;
res.send(results);
});
});
router.get('/users/:id', (req, res) => {
const { id } = req.params;
pool.query('SELECT * FROM users WHERE id = ?', id, (error, results) => {
if (error) throw error;
res.send(results[0]);
});
});
router.post('/users', (req, res) => {
const { name, email } = req.body;
pool.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], (error, results) => {
if (error) throw error;
res.send(`User added with ID: ${results.insertId}`);
});
});
router.put('/users/:id', (req, res) => {
const { id } = req.params;
const { name, email } = req.body;
pool.query('UPDATE users SET name = ?, email = ? WHERE id = ?', [name, email, id], (error, results) => {
if (error) throw error;
res.send(`User modified with ID: ${id}`);
});
});
router.delete('/users/:id', (req, res) => {
const { id } = req.params;
pool.query('DELETE FROM users WHERE id = ?', id, (error, results) => {
if (error) throw error;
res.send(`User deleted with ID: ${id}`);
});
});
module.exports = router;
In this example, we start by requiring the express
and mysql
modules, and creating a MySQL connection pool using mysql.createPool()
. The connection pool is a best practice for managing database connections in Node.js, as it allows you to reuse database connections rather than creating a new connection for each request.
We then define endpoints for a CRUD API, including GET /users
, GET /users/:id
, POST /users
, PUT /users/:id
, and DELETE /users/:id
. Each endpoint handles a different CRUD operation and makes use of the pool.query()
method to interact with the MySQL database.
For example, the GET /users
endpoint selects all rows from the users
table and sends the results back to the client using res.send()
. The GET /users/:id
endpoint selects a single row from the users
table based on the id
parameter in the URL, and sends the result back to the client.
Similarly, the POST /users
endpoint inserts a new row into the users
table using the name
and email
parameters from the request body. The PUT /users/:id
endpoint updates an existing row in the users
table based on the id
parameter in the URL and the name
and email
parameters from the request body. The DELETE /users/:id
endpoint deletes a row from the users
table based on the id
parameter in the URL.
Finally, we export the router using module.exports
, so that it can be imported and we can use it.
Test your application
Run your Node.js server by running node server.js
in the command line. Test your application’s endpoints using a tool like Postman or curl.
Deploy your application
When you are ready to deploy your application to a production environment, you will need to choose a hosting provider and configure your application for deployment. You might use a platform like Heroku or AWS, or deploy your application to your own server.