I have set up the Heroes example up to step 10. Http Client. I've run the example to, which runs fine. Now, I'm replacing the "dummy" server with a Node.JS server on port 3002, replacing the _HeroesURL to "http:/localhost:3002/hero". The GET since then runs fine, the POST (attached to addHero) gets called twice into an error?
My Node.js server:
var dbHeroes = [
{"id": 11, "name": "Mr. Nice"},
{"id": 12, "name": "Narco"},
{"id": 13, "name": "Bombasto"},
{"id": 14, "name": "Celeritas"},
{"id": 15, "name": "Magneta"},
{"id": 16, "name": "RubberMan"},
{"id": 17, "name": "Dynama"},
{"id": 18, "name": "Dr IQ"},
{"id": 19, "name": "Magma"},
{"id": 20, "name": "Tornado"}]
var id = 21;
var http = require('http');
http.createServer(function (req, res) {
// approve XHR-requests
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Headers", "Content-type");
res.setHeader("Access-Control-Request-Method","GET POST");
// set up some routes
switch (req.url) {
case "/hero":
switch (req.method) {
case "GET":
// getting heroes
res.writeHead(200, "OK", {'Content-Type': 'application/json'});
res.write(JSON.stringify(dbHeroes));
res.end();
break;
case "OPTIONS":
// pre-flight request (XHR)
res.writeHead(200, "OK", {'Content-Type': 'text/plain'});
res.end('Allow: GET POST');
break;
case "POST":
var body = '';
// get a chunk of the body
req.on("data", function(chunk) {
body += chunk;
})
// body finished
req.on("end", function () {
var newHero = JSON.parse(body);
console.log("recieved hero: " + body);
newHero.id = id++;
console.log("hero is now:" + JSON.stringify(newHero));
dbHeroes.push(newHero);
res.writeHead(200, "OK", {'Content-Type': 'application/json'});
res.write(JSON.stringify(newHero));
res.end();
})
break;
default:
console.log(" [501] Request: unknown method " + req.method);
res.writeHead(501, "Not implemented", {'Content-Type': 'text/html'});
res.end('<html><head><title>501 - Not implemented</title></head><body><h1>Not implemented!</h1></body></html>');
break;
}
break;
default:
// return not found on all other routes
res.writeHead(404, "Not found", {'Content-Type': 'text/html'});
res.end("<html><head>404 Not Found</head>
<body><h1>Not Found</h1>The requested url was not found.</body>
</html>");
};}).listen(3002); // listen on tcp port 3002 (all interfaces)