Created
February 23, 2019 21:13
-
-
Save luismartinezs/26350c4965bdd4fc0286953ea1657f59 to your computer and use it in GitHub Desktop.
Nodejs custom middlewares #nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Middlewares created while learning nodejs/express | |
const express = require('express'); | |
const fs = require('fs'); | |
const path = require('path'); | |
require('dotenv').config(); | |
const app = express(); | |
// Custom middlewares: | |
// Middleware that logs hello in console | |
const helloMiddleWare = (req, res, next) => { | |
res.send('hello'); | |
next(); | |
}; | |
// Middleware that does the same as app.get | |
const customGet = (relPath, handler) => { | |
return (req, res, next) => { | |
if (req.method === 'GET' && req.path === relPath) { | |
handler(req, res, next); | |
} else { | |
next(); | |
} | |
}; | |
}; | |
// Middleware that does the same as express.static middleware; | |
const customStatic = folderPath => { | |
return (req, res, next) => { | |
if (req.method === 'GET') { | |
const fullPath = path.join(folderPath, req.path); | |
if (fs.existsSync(fullPath)) return res.sendFile(path.resolve(fullPath)); | |
} | |
return next(); | |
}; | |
}; | |
// Middleware that proxies any request whose path starts with '/api' to another url | |
const customProxy = (req, res, next) => { | |
if (/^\/api\//.test(req.path)) { | |
const newUrl = `${baseUrl}${req.path.slice(5)}`; | |
const options = { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify(req.body) | |
}; | |
return fetch(newUrl, options) | |
.then(proxyRes => proxyRes.json()) | |
.then(proxyRes => { | |
res.json(proxyRes); | |
}) | |
.catch(err => { | |
res.status(500).send(); | |
}); | |
} | |
return next(); | |
}; | |
// Routes: | |
app.use(customProxy); | |
app.use(customStatic('static')); | |
app.use(customGet('/', (req, res) => { | |
res.sendFile('index.html'); | |
})) | |
// Listen to port: | |
const listener = app.listen(3000, () => { | |
console.log(`Your app is listening on port ${listener.address().port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment