Created
December 28, 2019 16:46
-
-
Save sagarpanda/5f33678ecccd3e1d5a4976be20f9f3c8 to your computer and use it in GitHub Desktop.
Handle POST and GET request method in http server
This file contains hidden or 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
| var http = require('http'); | |
| var url = require('url'); | |
| function processPost(request, response, callback) { | |
| var queryData = ""; | |
| if(typeof callback !== 'function') return null; | |
| if(request.method == 'POST') { | |
| request.on('data', function(data) { | |
| queryData += data; | |
| if(queryData.length > 1e6) { | |
| queryData = ""; | |
| response.writeHead(413, {'Content-Type': 'text/plain'}).end(); | |
| request.connection.destroy(); | |
| } | |
| }); | |
| request.on('end', function() { | |
| request.post = JSON.parse(queryData);; | |
| callback(request.post); | |
| }); | |
| } else { | |
| response.writeHead(405, {'Content-Type': 'text/plain'}); | |
| response.end(); | |
| } | |
| } | |
| http.createServer(function (req, res) { | |
| console.log('req.url: ', req.url); | |
| console.log('req.method: ', req.method); | |
| if (req.method == 'POST') { | |
| processPost(req, res, (data) => { | |
| console.log('data: ', data); | |
| res.writeHead(200, {'Content-Type': 'application/json'}); | |
| res.write(JSON.stringify(data)); | |
| res.end(); | |
| }); | |
| } else if(req.method == 'GET') { | |
| var url_parts = url.parse(req.url, true); | |
| var query = url_parts.query; | |
| res.writeHead(200, {'Content-Type': 'application/json'}); | |
| res.write(JSON.stringify(query)); | |
| res.end(); | |
| } else { | |
| res.write('Hello World!'); | |
| res.end(); | |
| } | |
| }).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment