Angular2 英雄示例在与节点.js服务器结合使用时使 POST 翻倍

Angular2 Heroes example doubles POST when combined with node.js server

本文关键字:结合 翻倍 POST 服务器 js 英雄 节点 Angular2      更新时间:2023-09-26

我已经设置了英雄示例到步骤 10。Http 客户端。我已经运行了示例,运行良好。现在,我将端口 3002 上的 Node.JS 服务器替换"虚拟"服务器,将_HeroesURL替换为"http:/localhost:3002/hero"。从那以后的 GET 运行良好,POST(附加到 addHero)被调用两次出错?

我的节点.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)

找到答案:BrowserSync 发现 Angular2-app 的两个实例正在运行,并在两个实例上同步了按钮的点击。通过关闭此"功能"来修复....