首页 > 解决方案 > 指定主机名时在 node.js 中出现 EADDRINUSE 错误

问题描述

尝试运行此代码时,我在 nodejs 上收到 EADDRINUSE 错误:

const express = require('express')
const http = require('http')    
const hostname = 'localhost'
const port = 3000

const app = express()

app.use((req, res, next) => {
    console.log(req.headers)
    res.statusCode = 200
    res.setHeader('Content-Type', 'text/html')
    res.end('<html><body><h1>This is response</h1></body></html>')
})

server.listen(hostname,port, () => {
    console.log(`Server running at http:${hostname}//:${port}`)
})

const server = http.createServer(app)

server.listen(hostname,port, () => {
    console.log(`Server running at http:{}//:${port}`)
})

我尝试更改端口,但仍然出现相同的错误。奇怪的是,如果我删除主机名 - “localhost”并且只听端口代码工作。

请解释可能是什么问题?

这是堆栈跟踪:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE localhost
    at Object._errnoException (util.js:1022:11)
    at _exceptionWithHostPort (util.js:1044:20)
    at Server.setupListenHandle [as _listen2] (net.js:1350:19)
    at listenInCluster (net.js:1408:12)
    at Server.listen (net.js:1503:5)
    at Object.<anonymous> (/media/shikhar/D/Study/git-test/node-express/index.js:30:8)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)

标签: javascriptnode.jsexpresslocalhost

解决方案


推荐阅读