Home > Web Front-end > JS Tutorial > Why Am I Getting the 'Error: listen EADDRINUSE' When Running a Node.JS Server?

Why Am I Getting the 'Error: listen EADDRINUSE' When Running a Node.JS Server?

Susan Sarandon
Release: 2024-11-19 13:03:03
Original
339 people have browsed it

Why Am I Getting the

Fixing Error: EADDRINUSE while Using Node.JS

Issue Overview:

When attempting to run a server on port 80 while performing a request using XMLHttpRequest, the error "Error: listen EADDRINUSE" may occur in Node.JS. This error indicates that the server is unable to bind to the specified port because another process is already using it.

Why it's a Problem:

Node.JS requires exclusive use of the port it binds to, preventing requests from being made while the server is running. Browsers can connect to the server and make requests because they use ephemeral ports.

Server Implementation:

net.createServer(function (socket) {
    socket.name = socket.remoteAddress + ":" + socket.remotePort;
    console.log('connection request from: ' + socket.remoteAddress);
    socket.destroy();
  }).listen(options.port);
Copy after login

Request Code:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    sys.puts("State: " + this.readyState);

    if (this.readyState == 4) {
        sys.puts("Complete.\nBody length: " + this.responseText.length);
        sys.puts("Body:\n" + this.responseText);
    }
};

xhr.open("GET", "http://mywebsite.com");
xhr.send();
Copy after login

Solution:

To resolve this issue, it is necessary to ensure that no other process is binding to port 80. This can be achieved by killing the offending process using the following command:

killall -9 node
Copy after login

Caution: This command will terminate all running Node.JS processes, so use it with caution.

Verifying Termination:

To verify that the process has been terminated, run the following command:

ps ax
Copy after login

If no Node.JS processes are listed, the issue should be resolved.

The above is the detailed content of Why Am I Getting the 'Error: listen EADDRINUSE' When Running a Node.JS Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template