Sample Express Server
January 22, 2020
This is a test
// Dependencies
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;
// Sets up the Express app to handle data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
// note: You don't have to specify `public` in your path
app.use(express.static(path.join(__dirname, 'public')));
// Data
const characters = [
{
routeName: 'yoda',
name: 'Yoda',
role: 'Jedi Master',
age: 900,
forcePoints: 2000,
},
{
routeName: 'darthmaul',
name: 'Darth Maul',
role: 'Sith Lord',
age: 200,
forcePoints: 1200,
},
{
routeName: 'obiwankenobi',
name: 'Obi Wan Kenobi',
role: 'Jedi Master',
age: 55,
forcePoints: 1350,
},
];
// Routes
app.get('/', function(req, res) {
res.send('Welcome to the Star Wars Page!');
});
// Displays all characters
app.get('/api/characters', function(req, res) {
return res.json(characters);
});
// Displays a single character, or shows "No character found"
app.get('/api/characters/:character', function(req, res) {
const chosen = req.params.character;
console.log(chosen);
for (var i = 0; i < characters.length; i++) {
if (chosen === characters[i].routeName) {
return res.json(characters[i]);
}
}
return res.send('No character found');
});
// Create New Characters - takes in JSON input
app.post('/api/characters', function(req, res) {
const newCharacter = req.body;
console.log(newCharacter);
characters.push(newCharacter);
res.json(newCharacter);
});
app.listen(PORT, console.log(`Server started on port ${PORT}`));