Last active
March 2, 2016 09:58
-
-
Save dimified/2424a0e0c196f2fb0835 to your computer and use it in GitHub Desktop.
Simple 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'), | |
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