Last active
March 29, 2018 11:49
-
-
Save dannysofftie/4d4cc28189fa384a97ac8f26bfec5109 to your computer and use it in GitHub Desktop.
Nodejs server without express or any framework. Handle GET and POST
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
/* | |
*I will share how you can achieve the below: | |
*Handle GET and POST requests in Nodejs without using a framework. | |
*Serve static files from a public folder (css, js, images). | |
*/ | |
const http = require('http') | |
const fs = require("fs") | |
const path = require("path") | |
const port = process.env.PORT || 4000 | |
http.createServer((req, res) => { | |
switch (req.method) { | |
// serve get requests | |
case "GET": | |
// this is a request to the home page, return index.html | |
if (req.url === '/') { | |
fs.createReadStream(path.join(__dirname + 'index.html')).pipe(res) | |
} | |
// call the function that serves static files, passing req, and res parameters | |
serveStaticFiles(req, res) | |
break; | |
// serve post requests | |
case "POST": | |
if (req.url === '/postrequest') { | |
req.on('data', (chunk) => { | |
// you can access data sent via post i.e | |
let data = chunk.toString() // converting to string because Node receives data as a buffer | |
// do some processing and send back response | |
res.end(JSON.stringify({ 'message' : 'data received and processed' })); | |
}); | |
} | |
break; | |
default: | |
// you can have an error page if requests don't match above | |
fs.createReadStream(path.join(__dirname + '/error.html')).pipe(res); | |
break; | |
} | |
}).listen(port, () => console.log(`Server listening at port: ${port}`)) | |
// function to serve static files, js, css, images and the likes | |
function serveStaticFiles(req, res) { | |
// specifying root path e.g. 'public' in this case will only allow serving files within the public folder and disable directory listing of other files | |
let rootPath = path.join('public' + req.url), | |
mimeType = Object.create({ | |
'.js': 'text/javascript', | |
'.css': 'text/css' | |
}) | |
// check if file exists in public folder | |
fs.existsSync(rootPath) ? (function () { | |
// file found, return status 200 plus the file content | |
fs.readFile(rootPath, (err, data) => { | |
err ? (function () { | |
res.writeHead(500, 'Internal server error', { 'Content-Type': 'text/plain' }); | |
res.end() | |
})() : (function () { | |
res.writeHead(200, { 'Content-Type': mimeType[path.extname(rootPath)] }) | |
res.end(data) | |
})(); | |
}); | |
})() : (function () { | |
// file not found and thus return 504 | |
res.writeHead(404, 'Ruquested file not found') | |
res.end() | |
})() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment