0

ステップ 10 までのヒーローの例をセットアップしました。 HTTP クライアント。例を実行しましたが、問題なく動作します。ここで、「ダミー」サーバーをポート 3002 の Node.JS サーバーに置き換え、_HeroesURL を「http:/localhost:3002/hero」に置き換えます。それ以降の GET は正常に実行され、POST (addHero に接続) が 2 回呼び出されてエラーになりますか?

私の Node.js サーバー:

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)
4

1 に答える 1