简体   繁体   中英

express api, why do I get Error: listen EADDRINUSE :::5000

I'm creating a simple express api using this code

//server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.json());

const db = require('./config/keys').mongoURI;

mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log('db connected'))
  .catch(err => console.error(err))

const port = process.env.PORT || 5000;

app.listen(port, () => console.log('server connected'))



//config/keys.js
module.exports = {
  mongoURI: 'mongodb://db address'
};

When I run it or make changes to the file I always get an error

Error: listen EADDRINUSE :::5000
    at Server.setupListenHandle [as _listen2] (net.js:1327:14)
    at listenInCluster (net.js:1375:12)
    at Server.listen (net.js:1462:7)
    at Function.listen (/Users/user/Desktop/mern-2/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/Users/user/Desktop/mern-2/server.js:18:5)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:238:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
Emitted 'error' event at:
    at emitErrorNT (net.js:1354:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:746:11)
    at startup (internal/bootstrap/node.js:238:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)

I can fix this by running lsof -i :5000 and then kill the node returned

Why do I get this error and is there a way to stop it

The error Error: listen EADDRINUSE :::5000 is self descriptive.

Looks like another application is listening to the port 5000 , or another instance of your same app is already running in the system.

Your solution of killing the process works - because there you kill the process which is listening to the port 5000.

It is not immediately clear from the information given if it is another instance of your own app or if it is a different app which uses the port 5000.

If it is another app (which you can figure out by looking at lsof -i -n -P ), you should use another port.

If it is another instance of your own app, make sure you terminate the running instance ( Ctrl + C ) before editing.

Maybe you can use Nodemon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM