express js:端口运行,但不能杀死端口



当我尝试运行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 killkillall 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上运行的服务器(因为这里使用的就是这个服务器)。lsof生成的表中的第二列是进程号。现在可以运行kill -9 <process number>了。之后,您的应用程序应该可以工作

最新更新