Addressing Error: listen EADDRINUSE in Node.js
The "Error: listen EADDRINUSE" issue arises when Node.js encounters an attempt to listen on an already occupied port. Node.js is a runtime environment for executing JavaScript applications.
In the provided scenario, a server is listening on port 80 while simultaneously attempting to use XMLHttpRequest for a request. Browsers can handle concurrent connections, but the Node.js server faces an issue due to the port's unavailability.
The server code, as mentioned:
net.createServer(function (socket) { socket.name = socket.remoteAddress + ":" + socket.remotePort; console.log('connection request from: ' + socket.remoteAddress); socket.destroy(); }).listen(options.port);
The server is essentially listening for incoming connections but immediately destroying them. This prevents any actual requests from being processed.
The request code, as provided:
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();
The request is attempting to make an HTTP GET request to a remote website while the Node.js server is running on port 80.
To resolve the "Error: listen EADDRINUSE", the server should either:
The above is the detailed content of Why Does Node.js Throw 'Error: listen EADDRINUSE' When Using XMLHttpRequest?. For more information, please follow other related articles on the PHP Chinese website!