Express JSON REST API with a MySQL database
Recently, I was looking into creating some new views for a older PHP-centric application. Rather than trying to extend the old codebase, I decided to create a separate single page app with Angular 2. Instead of querying the database directly on the server side, I needed to be able to access this over a AJAX call.
I was genuinely surprised how straightforward it was expose the data with the Express framework. All that is needed to make a call is to set up the database connection and a bit of boilerplate to describe the endpoints.
import express = require("express");
import mysql = require("mysql");
let connection = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "database"
});
connection.connect();
const app = express();
app.get("/api/customer/:id", (req, res) => {
const id = req.params.id;
connection.query(`SELECT * FROM customers
WHERE id = ${id}
ORDER BY id DESC`,
(err, rows, fields) => {
if (err){
res.json(err);
}
res.json(rows);
});
});
const port = process.env.PORT || 3001;
var server = app.listen(port, () => {
var port = server.address().port;
console.log("This express app is listening on port:" + port);
});