Skip to content

Instantly share code, notes, and snippets.

@dimified
Last active March 2, 2016 09:58
Show Gist options
  • Save dimified/2424a0e0c196f2fb0835 to your computer and use it in GitHub Desktop.
Save dimified/2424a0e0c196f2fb0835 to your computer and use it in GitHub Desktop.
Simple HTTP server
var http = require('http'),
dispatcher = require('httpdispatcher'),
PORT = 3000;
dispatcher.onGet('/', function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Server running');
});
dispatcher.onGet('/json', function (req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
id: 0,
name: 'name'
}));
});
function handleRequest(req, res) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9000');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
try {
console.log(req.url);
dispatcher.dispatch(req, res);
} catch (err) {
console.log(err);
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function () {
console.log('Server listening on localhost:%s', PORT);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment