Skip to content

Instantly share code, notes, and snippets.

@santiagocodes
Created June 5, 2019 10:25
Show Gist options
  • Save santiagocodes/6b07ff78e1c67e325c1970fb51080b81 to your computer and use it in GitHub Desktop.
Save santiagocodes/6b07ff78e1c67e325c1970fb51080b81 to your computer and use it in GitHub Desktop.
Express 2 - Express, SQL-MySQL, Postman. Creating an API for movies (https://gist.github.com/AlexLoWCD/bd426b7416d3afde85e65fbe7821acfc)
const mysql = require('mysql');
var express = require('express');
const connection = mysql.createConnection({
host : 'localhost', // address of the server
user : 'blablabla', // username
password : 'blablabla',
database : 'express_2',
});
const app = express();
const port = 3000
// A route matching the url /api/movies that sends all the movies from the movie table.
app.get('/api/movies/', (req, res) => {
// connection to the database, and selection of movie table
connection.query('SELECT * FROM movie', (err, results) => {
if (err) {
// If an error has occurred, then the user is informed of the error
res.status(500).send('Error while retrieving movies');
} else {
// If everything went well, we send the result of the SQL query as JSON.
res.json(results);
}
});
});
// A route /api/movies/names that only sends the names of the movies.
app.get('/api/movies/names', (req, res) => {
// connection to the database, and selection movie names from movie table
connection.query('SELECT name FROM movie', (err, results) => {
if (err) {
// If an error has occurred, then the user is informed of the error
res.status(500).send('Error while retrieving movies');
} else {
// If everything went well, we send the result of the SQL query as JSON.
res.json(results);
}
});
});
app.listen(port, () => console.log(`App listening on port ${port}!`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment