express js: port 运行 但无法杀死端口

express js: port running but not able to kill port

当我尝试 运行 nodemonindex.js 我得到这个错误我有 pm2 运行ning 但我的 localhost/5002 给出

[nodemon] starting `node index.js`
Listening on 5002
events.js:377
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5002
    at Server.setupListenHandle [as _listen2] (net.js:1331:16)
    at listenInCluster (net.js:1379:12)
    at Server.listen (net.js:1465:7)
    at Function.listen (/home/vivek/mycodes/ask-backend/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/vivek/mycodes/ask-backend/index.js:19:5)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1358:8)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 5002
}
[nodemon] app crashed - waiting for file changes before starting...

我尝试了 pm2 kill killall node 仍然端口没有死 我从 github 和 运行 提取我的代码后在新机器上我不知道是否db 是此错误的原因

index.js

var moment = require("moment");
var express = require("express");
var ObjectId = require("mongodb").ObjectID;
const { ExploreTrendRequest } = require("g-trends");
var bodyParser = require("body-parser");
var app = express();

// if (process.env.NODE_ENV == "production") {
//   app.use(express.static("portfolio/build"));
//   const path = require("path");
//   app.get("*", (req, res) => {
//     res.sendFile(path.resolve(__dirname, "portfolio", "build", "index.html"));
//   });
// }
const PORT = process.env.PORT || 5002;

express().listen(PORT, () => console.log(`Listening on ${PORT}`));

app.listen(process.env.PORT || 5002);
const multer = require("multer");
const upload = multer();
var bodyParser = require("body-parser");

app.use(express.json());
var MongoClient = require("mongodb").MongoClient;
var id = require("mongodb").ObjectID;

//Create a database named "mydb":    sudo service mongod start
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
  if (err) throw err;

  var mydb = db.db(mydb);
  var created = moment().format("YYYY-MM-DD hh:mm:ss");

  // mydb.createCollection("questions", function (err, data) {
  // if (err) throw err;
  // var question = {
  //   question: "the first question",
  //   time: created,
  // };
  // mydb.collection("questions").insertOne(question, function (err, data) {
  //   if (err) throw err;
  //   console.log("Data created!");

  app.use(function (req, res, next) {
    // Website you wish to allow to connect
    res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");

    // Request methods you wish to allow
    res.setHeader(
      "Access-Control-Allow-Methods",
      "GET, POST, OPTIONS, PUT, PATCH, DELETE"
    );

    // Request headers you wish to allow
    res.setHeader(
      "Access-Control-Allow-Headers",
      "X-Requested-With,content-type"
    );

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader("Access-Control-Allow-Credentials", true);

    // Pass to next layer of middleware
    next();
  });
  app.use(express.urlencoded({ extended: true }));
  app.post("/questionpost", function (req, res) {
    let formData = req.body;
    // let bodyJson = JSON.parse(formData);
    console.log(formData);

    mydb.collection("questions").insertOne(formData, (err, result) => {
      if (err) {
        res.send({ error: "Ann error has occured" });
      } else {
        res.send(result.ops[0]);
      }
    });
  });

  app.post("/answerpost", function (req, res) {
    let formData = req.body;
    // let bodyJson = JSON.parse(formData);
    // console.log(formData);

    mydb.collection("answers").insertOne(formData, (err, result) => {
      if (err) {
        res.send({ error: "Ann error has occured" });
      } else {
        res.send(result.ops[0]);
      }
    });
  });

  app.get("/answersapi/:gotid", function (req, res) {
    let id = req.params.gotid;
    console.log(id);
    mydb
      .collection("answers")
      .find({ question_id: id })
      .toArray(function (err, data) {
        if (err) throw error;
        res.send(data);
      });
  });

  // mydb
  //   .collection("questions")
  //   .insertOne(formData)
  //   .toArray(function (err, res) {
  //     if (err) throw err;
  //     console.log("1 document inserted");
  //   });
  // res.send(res);

  // app.post("/questionpost", jsonParser, function (req, res) {
  //   let data = req;
  //   console.log(data);
  // });

  app.get("/questapi", function (req, res) {
    console.log("apicalled");

    mydb
      .collection("questions")
      .find({})
      .toArray(function (err, data) {
        if (err) throw error;
        res.send(data);
      });
  });

  //http://localhost:5002/answerpost
  // increment;

  app.post("/increment", function (req, res) {
    let id = req.body;
    var correctcount = id.correctcount + 1;
    //var ansid = id.Answer_id;
    var realid = ObjectId(id.Answer_id);
    console.log(correctcount);

    // var myquery = { address: "Valley 345" };
    // var newvalues = { $set: { name: "Mickey", address: "Canyon 123" } };
    // dbo
    //   .collection("customers")
    //   .updateOne(myquery, newvalues, function (err, res) {
    //     if (err) throw err;
    //     console.log("1 document updated");
    //     db.close();
    //   });

    mydb
      .collection("answers")
      .updateOne(
        { _id: realid },
        { $set: { correctcount: correctcount } },
        function (err, data) {
          if (err) throw err;
          console.log("1 document updated");
          res.send(data);
        }
      );
  });

  app.post("/decrementer", function (req, res) {
    let id = req.body;
    var wrongcount = id.wrongcount - 1;
    //var ansid = id.Answer_id;
    var realid = ObjectId(id.Answer_id);
    console.log(wrongcount);

    // var myquery = { address: "Valley 345" };
    // var newvalues = { $set: { name: "Mickey", address: "Canyon 123" } };
    // dbo
    //   .collection("customers")
    //   .updateOne(myquery, newvalues, function (err, res) {
    //     if (err) throw err;
    //     console.log("1 document updated");
    //     db.close();
    //   });

    mydb
      .collection("answers")
      .updateOne(
        { _id: realid },
        { $set: { wrongcount: wrongcount } },
        function (err, data) {
          if (err) throw err;
          console.log("1 document updated");
          res.send(data);
        }
      );
  });

  app.get("/questone/:gotid", function (req, res) {
    let id = req.params.gotid;
    // /console.log(id);
    mydb
      .collection("questions")
      .find({ _id: ObjectId(id) })
      .toArray(function (err, data) {
        if (err) throw error;
        //console.log(data);
        res.send(data);
      });
  });

  //trend api call

  app.post("/trend", function () {
    const explorer = new ExploreTrendRequest();
    console.log("api calling 1");
    explorer
      .addKeyword("Dream about snakes")
      .compare("Dream about falling")
      .download()
      .then((csv) => {
        console.log(
          "[✔] Done, take a look at your beautiful CSV formatted data!"
        );
        console.log(csv);
      })
      .catch((error) => {
        console.log("[!] Failed fetching csv data due to an error", error);
      });
  });
});

我已将我的 index.js 发布在这里,以便您可以参考错误是什么

如果它在另一台计算机上工作,这可能不是您的应用程序的问题。该端口已被另一个进程使用。可能是另一个应用程序。你要做的是

  1. 确定已经在使用该端口的进程
  2. 干掉它

如果您使用 Mac,则首先要 运行 宁 sudo lsof -i -P | grep LISTEN。这将列出正在侦听任何端口的所有进程。在端口 5002 上找到一个 运行ning(因为这是您在这里使用的那个)。 lsof 生成的 table 中的第二列是进程号。现在你可以 运行 kill -9 <process number>。之后你的应用程序应该工作