Skip to content

Instantly share code, notes, and snippets.

@piyushgarg195

piyushgarg195/index.js

Last active Apr 22, 2020
Embed
What would you like to do?
// Import the Express using require() module
const express = require('express');
// Initalize express app
const app = express();
// Lets create Fake Data for api
const userData = [
{
id: 1,
name: 'Jhon',
age: 20
},
{
id: 2,
name: 'Jane',
age: 23
},
{
id: 3,
name: 'Tim',
age: 34
},
];
// Create Endpoints for API
// Endpoint 1
app.get('/api', function(req, res){
res.send('Welcome to our API')
})
// Endpoint 2
app.get('/api/users', function(req, res){
res.json(userData);
})
// Endpoint 3
app.get('/api/user/:id', function(req, res){
const id = req.params.id;
const user = userData.find(user => user.id == id);
if (user) {
res.json(user)
}
else {
res.send('No User Found')
}
})
// Start the Server
const PORT = 3000;
app.listen(PORT, function(){
console.log('Server Started')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.