nodemon session-cookie.js
> 127.0.0.1:8000
# visit /login
> Redirects to /admin with cookie
# visit /logout
> Redirects to / with cookie deleted
Last active
March 2, 2018 03:27
-
-
Save bencooling/c07cd26bc0906c36cd9279f4a4fb11ac to your computer and use it in GitHub Desktop.
javascript: http server
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
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