gugu-car-crud-api
Version:
Car-crud-api
94 lines (78 loc) • 2.52 kB
JavaScript
const express = require("express");
const mysql = require("mysql2");
const app = express();
app.use(express.json());
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Letsdoit!',
database: 'CAR'
});
con.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
} else {
console.log("The server is connected");
}
});
app.post('/cars', (req, res) => {
const { Brand, Transmission, Color, YearModel } = req.body;
con.query(
'INSERT INTO CarTable (Brand, Transmission, Color, YearModel) VALUES (?, ?, ?, ?)',
[Brand, Transmission, Color, YearModel],
(err, results) => {
if (err) {
console.error('Error inserting data:', err);
res.status(500).send("Error inserting data");
} else {
res.send("Car added successfully");
}
}
);
});
app.get('/cars', (req, res) => {
con.query('SELECT * FROM CarTable', (err, results) => {
if (err) {
console.error('Error fetching data:', err);
res.status(500).send("Error fetching data");
} else {
res.json(results);
}
});
});
app.put('/cars/:id', (req, res) => {
const id = req.params.id;
const { Brand, Transmission, Color, YearModel } = req.body;
con.query(
'UPDATE CarTable SET Brand = ?, Transmission = ?, Color = ?, YearModel = ? WHERE id = ?',
[Brand, Transmission, Color, YearModel, id],
(err, results) => {
if (err) {
console.error('Error updating data:', err);
res.status(500).send("Error updating the car");
} else {
res.send("Car updated successfully");
}
}
);
});
app.delete('/cars/:id', (req, res) => {
const id = req.params.id;
con.query('DELETE FROM CarTable WHERE id = ?', [id], (err, results) => {
if (err) {
console.error('Error deleting data:', err);
res.status(500).send("Error deleting the car");
} else if (results.affectedRows === 0) {
res.status(404).send("No record found with the given ID");
} else {
res.send("Car deleted successfully");
}
});
});
app.listen(3001, (err) => {
if (err) {
console.error('Error starting the server:', err);
} else {
console.log("Server is running on port 3001");
}
});