Skip to content

Instantly share code, notes, and snippets.

@indongyoo
Last active April 4, 2018 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indongyoo/2ecbb66675b931e730d6cb44b0f72a79 to your computer and use it in GitHub Desktop.
Save indongyoo/2ecbb66675b931e730d6cb44b0f72a79 to your computer and use it in GitHub Desktop.
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const getBody = req => new Promise(function(resolve) {
let body = '';
req.on('data', data => body += data);
req.on('end', _ => resolve(
req.headers['content-type'] === 'application/json' ?
JSON.parse(body) : querystring.parse(body)
));
});
http.createServer(async (req, res) => {
const method = req.method;
const uri = url.parse(req.url, true);
onRequest(
res,
method,
uri.pathname,
method === 'POST' || method === 'PUT' ? await getBody(req) : uri.query
);
}).listen(8000);
const onRequest = (res, method, pathname, params) => res.end(JSON.stringify(params));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment