Skip to content

Instantly share code, notes, and snippets.

@bencooling
Last active March 2, 2018 03:27
Show Gist options
  • Save bencooling/c07cd26bc0906c36cd9279f4a4fb11ac to your computer and use it in GitHub Desktop.
Save bencooling/c07cd26bc0906c36cd9279f4a4fb11ac to your computer and use it in GitHub Desktop.
javascript: http server

session-cookie.js

nodemon session-cookie.js
> 127.0.0.1:8000
# visit /login
> Redirects to /admin with cookie
# visit /logout
> Redirects to / with cookie deleted
const http = require('http');
const { graphql, buildSchema } = require('graphql');
const PORT = 8000;
const settings = { colors: true, depth: null };
const getBody = req => new Promise((resolve, reject) => {
const body = "";
req.on('data', chunk => body += chunk);
req.on('end', () => resolve(body));
});
const routes = {
'/': {
get: (req, res) => Promise.resolve({ body: 'get' }),
post: (req, res) =>
getBody(req).then(body => ({ body: JSON.stringify({ url: req.url }) })),
},
'#': () => Promise.resolve({ statusCode: 404, body: 'Not Found' })
};
const handler = (req, res) => {
const { method, url } = req;
const defaults = {
body: '',
headers: { 'Content-Type': 'text/plain' },
statusCode: 200
};
const route = (routes[url]) ? routes[url][method.toLowerCase()] : routes['#'];
route(req, res).then(data => {
const { body, headers, statusCode } = Object.assign(defaults, data);
res.writeHead(statusCode, headers);
res.write(body);
res.end();
});
};
const server = http.createServer(handler);
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(PORT, () => {
console.log('Server listening on: %s', PORT);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment