我知道我的问题被重复了。在标记为重复或任何其他内容之前,请完整阅读问题。
我正在学习node.js来创建rest api并做得很好。一切都很顺利,直到我在重新启动应用程序时发现了这个错误(EADDRINUSE)。这个问题占用了我宝贵的时间,但仍然无法找到正确的解决方案。
如果应用程序第一次运行,它会顺利启动,无需更改任何端口,由于某种原因,我们会停止或重新启动应用程序,同时从服务器抛出此错误消息。他们中的许多人建议只更改端口,一切都会顺利进行,我同意他们的观点。但是当服务器在全局范围内运行和使用时,您无法更改端口以重新启动。
添加我的代码片段。
app.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var config = require('./Config/config.js');
var api = require('./apis/api');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
app.all('/api/write/'+config.WRITE_API_VERSION+'/:apiName', function (req, res) {
api.handle.apply(null, ['write', req.method.toLowerCase(), req.params.apiName, req, res]);
console.log("in api end1"+req.body);
});
app.all('/api/read/'+config.READ_API_VERSION+'/:apiName', function (req, res) {
api.handle.apply(null, ['read', req.method.toLowerCase(), req.params.apiName, req, res]);
console.log("in api end2");
});
app.use(function (req, res, next) {
res.contentType('application/json');
next();
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(config.PORT);
console.log('Magic happens on port ' + config.PORT);
config.js
var configs = {
ENVIRONMENT: "development",
READ_API_VERSION: "v1.0",
WRITE_API_VERSION: "v1.0",
PORT: 8080
}
Object.freeze(configs);
module.exports = configs;
包.json
"scripts": {
"start": "node app.js"
}
错误信息
node app.js
Magic happens on port 8080
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at Server.listen (net.js:1135:5)
at EventEmitter.listen (/home/ubuntu/vcare_backend/VCare/node_modules/express/lib/application.js:617:24)
at Object.<anonymous> (/home/ubuntu/vcare_backend/VCare/app.js:47:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
运行命令 sudo netstat -plnt 后
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 3277/node
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1073/sshd
tcp6 0 0 :::22 :::* LISTEN 1073/sshd
最佳答案
您的问题是 Node 已在端口 8080 上运行。这由 netstat/lsof 命令返回的第一行显示。终止该进程将允许您重新启动 Node 进程。您可以使用命令
在 Mac 上执行此操作killall node
其中 Node 是进程的名称。
关于node.js - 重新启动 Node.Js 应用程序时会抛出 EADDRINUSE 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625102/