express js:端口正在运行但无法终止端口

Posted

技术标签:

【中文标题】express js:端口正在运行但无法终止端口【英文标题】:express js: port running but not able to kill port 【发布时间】:2021-11-24 02:41:12 【问题描述】:

当我尝试运行 nodemonindex.js 时出现此错误,我正在运行 pm2,但我的 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 拉出我的代码并在新机器上运行之后我不知道数据库是否是这个错误的原因

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】:

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

    识别已经在使用端口的进程 杀了它

如果您使用 Mac,请先运行 sudo lsof -i -P | grep LISTEN。这将列出正在侦听任何端口的所有进程。找到在端口 5002 上运行的那个(因为这是您在此处使用的那个)。 lsof 生成的表中的第二列是进程号。现在你可以运行kill -9 &lt;process number&gt;。之后您的应用程序应该可以工作了

【讨论】:

当我尝试 5003 时它也说同样的错误 sudo lsof -i -P | grep LISTEN 打印什么?你在运行什么操作系统?视窗? Linux?苹果系统?你如何开始你的申请? 我正在使用 ubuntu 18.4 现在我在 ubuntu 20..4 上构建这个应用程序 systemd-r 533 systemd-resolve 13u IPv4 24693 0t0 TCP localhost:53 (LISTEN) cupsd 790 root 6u IPv6 27989 0t0 TCP ip6-localhost:631 (LISTEN) cupsd 790 root 7u IPv4 27990 0t0 TCP localhost:631 (LISTEN) 节点 15294 vivek 23u IPv4 112428 0t0 TCP *:3000 (LISTEN) mongod 15760 mongodb 12u IPv4 118603 0t0 TCP localhost:27017 (LISTEN) nodemon index.js

以上是关于express js:端口正在运行但无法终止端口的主要内容,如果未能解决你的问题,请参考以下文章

express.js 服务器在正在使用的端口上启动

从运行在不同端口的 Vue 应用程序调用 node express 服务器 API

NodeJS Express - 同一端口上的两个 NodeJS 实例(vhost)

如何在同一个端口上运行 express 和 socket.io

如何在 Express.js 中强制 SSL / https

Express 应用程序中端口 3000 的意义