Skip to content

Instantly share code, notes, and snippets.

@potikanond
Last active February 4, 2020 05:27
Show Gist options
  • Save potikanond/2ad2d25267c4d77501ca0723f87927c5 to your computer and use it in GitHub Desktop.
Save potikanond/2ad2d25267c4d77501ca0723f87927c5 to your computer and use it in GitHub Desktop.
Simple Node Tutorial
const express = require('express');
const members = require('./Members');
// create application object
const app = express();
// 15 - body parser middleware to handle JSON
app.use(express.json());
// 15 - body parser middleware to handle URL encoded data
app.use(express.urlencoded( {extended: false}));
// create route handles
app.get('/', (req,res) => {
res.send('<h1>Hello World Dome<h1>'); // send HTML
});
// 4 - get all members
app.get('/api/members', (req,res) => {
res.json(members); // return JSON, no need to stringify
});
// 8 - get single member
app.get('/api/members/:id', (req, res) => {
//console.log(req.params.id); // get a param
// 12 - found id?
const found = members.some(member => member.id === parseInt(req.params.id));
if (!found) {
// 12 - what to do when not found
res.status(400).json({
msg: `No member with id of ${req.params.id}`
});
} else {
// 11
//res.json(members.filter(member => member.id === req.params.id)); // id is string
// 9 - arrow function with {} and 'return' statement
// res.json(members.filter(member => {
// return member.id === parseInt(req.params.id);
// }));
// 10 - arrow function withno {} and 'return' and ';'
res.json(members.filter(member =>
member.id === parseInt(req.params.id)
));
}
});
// run with 'process.env.PORT' otherwise port 5000
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}...`));
const { person, Person } = require('./person'); // import 'person.js'
console.log('Hello from Node.js...');
console.log(person);
const p1 = new Person('Dome Potikanond', 30);
p1.greeting();
// 4 - Array of member objects
const members = [
{
id: 1,
name: 'John Doe',
email: '[email protected]',
status: 'active'
},
{
id: 2,
name: 'Bob Williams',
email: '[email protected]',
status: 'inactive'
},
{
id: 3,
name: 'Shannon Jackson',
email: '[email protected]',
status: 'active'
}
];
module.exports = members;
const person = {
name: 'John Doe',
age: 30
}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greeting() {
console.log(`My name is ${this.name} (${this.age})`);
}
}
module.exports = {person, Person}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment