This post is a guidance for very beginners about a Node.js express code with mysql2 which shows some examples for CRUD in Node.js
//npm init
//npm install nodemon, mysql2, express, cors
const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const dbPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'database_name',
port: 3306,
});
app.get('/', (req, res) => {
res.send('Backend running');
});
// -------------- CRUD --------------
// CREATE
app.post('/api/users', async (req, res) => {
try {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'Error for the frontend (name or email missing)' });
}
const sql = "INSERT INTO users (name, email) VALUES (?, ?)";
const [result] = await dbPool.query(sql, [name, email]);
res.status(201).json({ message: "Response for the frontend", id: result.insertId });
} catch (error) {
console.error("Error for the backend ", error);
res.status(500).json({ error: 'Error for the frontend' });
}
});
// READ
app.get('/api/users', async (req, res) => {
try {
const sql = "SELECT id, name, email FROM users";
const [result] = await dbPool.query(sqlQuery);
res.json(result);
} catch (error) {
console.error("Error for the backend ", error);
res.status(500).json({ error: 'Error for the frontend' });
}
});
// UPDATE
app.patch('/api/users/:id', async (req, res) => {
try {
const { id } = req.params;
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'Error for the frontend (name or email missing)' });
}
const sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
const [result] = await dbPool.query(sql, [name, email, id]);
res.status(201).json({ message: "Response for the frontend", id: result.insertId });
} catch (error) {
console.error("Error for the backend ", error);
res.status(500).json({ error: 'Error for the frontend' });
}
});
// DELETE
app.delete('/api/users/:id', async (req, res) => {
try {
const { id } = req.params;
const sql = "DELETE FROM users WHERE id = ?";
const [result] = await dbPool.query(sql, [id]);
res.status(201).json({ message: "Response for the frontend", id: result.insertId });
} catch (error) {
console.error("Error for the backend ", error);
res.status(500).json({ error: 'Error for the frontend' });
}
});
const PORT = 3001;
app.listen(PORT, () => {
console.log('Server is running on: http://localhost:'+PORT);
});
Top comments (0)