formations/javascript/angular/exercices/services-1/server.js

53 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2015-04-07 22:38:36 +02:00
var http = require('http');
var server = http.createServer(function(req, res) {
res.setHeader('Content-Type', 'application/json; charset=utf8');
res.setHeader('Access-Control-Allow-Origin', '*');
if(req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'accept, content-type');
res.statusCode = 200;
return res.end();
}
if(req.method !== 'POST') {
res.statusCode = 400;
var content = JSON.stringify({message: "Méthode HTTP invalide !"}, null, 2);
return res.end( );
}
var data = '';
req.on('data', function(chunk) { data += chunk; });
req.once('end', function() {
try {
var obj = JSON.parse(data);
console.log('Données reçues', obj);
res.statusCode = 200;
return res.end(JSON.stringify({message: "OK"}, null, 2));
} catch(err) {
res.statusCode = 400;
var content = JSON.stringify({message: "Format des données invalide !"}, null, 2);
return res.end(content);
}
});
});
server.listen(3000, function(err) {
if(err) {
console.error(err.stack);
return process.exit(1);
}
console.log('Listening on http://localhost:3000');
});