javascript - 指定主机名时在 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)
解决方案
推荐阅读
- java - slf4j 在计划任务线程中不起作用
- android - 每次调用 onCreate 方法时都不会调用 ViewModel 方法
- python - 显示 pandas 列 - 从宽到长
- python - 从嵌套列表中删除不需要的文本
- php - 如何在电子邮件 Codeigniter 中循环收件人
- amazon-s3 - 如何处理包含“.”的存储桶路径 使用 gsutil
- javascript - 检测特定的嵌入脚本并将其删除?
- c++ - 如何在 Qt 的 .pro 中链接库 adshlp.h?
- json - 如何将我的会话或我的 GAN 模型保存到 js 文件中
- visual-studio - 如何创建默认不提供编号文件名的 VisualStudio 项模板