Error listen eaddrnotavail address not available

You will encounter various kinds of errors while developing Node.js applications, but most can be avoided or easily mitigated with the right coding practices. However, most of the information to fix these problems are currently scattered across various GitHub issues and forum posts which could lead to spending more time than necessary when seeking solutions.

You will encounter various kinds of errors while developing Node.js
applications, but most can be avoided or easily mitigated with the right coding
practices. However, most of the information to fix these problems are currently
scattered across various GitHub issues and forum posts which could lead to
spending more time than necessary when seeking solutions.

Therefore, we’ve compiled this list of 15 common Node.js errors along with one
or more strategies to follow to fix each one. While this is not a comprehensive
list of all the errors you can encounter when developing Node.js applications,
it should help you understand why some of these common errors occur and feasible
solutions to avoid future recurrence.

🔭 Want to centralize and monitor your Node.js error logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

1. ECONNRESET

ECONNRESET is a common exception that occurs when the TCP connection to
another server is closed abruptly, usually before a response is received. It can
be emitted when you attempt a request through a TCP connection that has already
been closed or when the connection is closed before a response is received
(perhaps in case of a timeout). This exception will usually
look like the following depending on your version of Node.js:

Output

Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at Socket.socketOnEnd (node:_http_client:466:23)
    at Socket.emit (node:events:532:35)
    at endReadableNT (node:internal/streams/readable:1346:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ECONNRESET'
}

If this exception occurs when making a request to another server, you should
catch it and decide how to handle it. For example, you can retry the request
immediately, or queue it for later. You can also investigate your timeout
settings if you’d like to wait longer for the request to be
completed.

On the other hand, if it is caused by a client deliberately closing an
unfulfilled request to your server, then you don’t need to do anything except
end the connection (res.end()), and stop any operations performed in
generating a response. You can detect if a client socket was destroyed through
the following:

app.get("/", (req, res) => {
  // listen for the 'close' event on the request
  req.on("close", () => {
    console.log("closed connection");
  });

  console.log(res.socket.destroyed); // true if socket is closed
});

2. ENOTFOUND

The ENOTFOUND exception occurs in Node.js when a connection cannot be
established to some host due to a DNS error. This usually occurs due to an
incorrect host value, or when localhost is not mapped correctly to
127.0.0.1. It can also occur when a domain goes down or no longer exists.
Here’s an example of how the error often appears in the Node.js console:

Output

Error: getaddrinfo ENOTFOUND http://localhost
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'http://localhost'
}

If you get this error in your Node.js application or while running a script, you
can try the following strategies to fix it:

Check the domain name

First, ensure that you didn’t make a typo while entering the domain name. You
can also use a tool like DNS Checker to confirm that
the domain is resolving successfully in your location or region.

Check the host value

If you’re using http.request() or https.request() methods from the standard
library, ensure that the host value in the options object contains only the
domain name or IP address of the server. It shouldn’t contain the protocol,
port, or request path (use the protocol, port, and path properties for
those values respectively).

// don't do this
const options = {
  host: 'http://example.com/path/to/resource',
};

// do this instead
const options = {
  host: 'example.com',
  path: '/path/to/resource',
};

http.request(options, (res) => {});

Check your localhost mapping

If you’re trying to connect to localhost, and the ENOTFOUND error is thrown,
it may mean that the localhost is missing in your hosts file. On Linux and
macOS, ensure that your /etc/hosts file contains the following entry:

You may need to flush your DNS cache afterward:

sudo killall -HUP mDNSResponder # macOS

On Linux, clearing the DNS cache depends on the distribution and caching service
in use. Therefore, do investigate the appropriate command to run on your system.

3. ETIMEDOUT

The ETIMEDOUT error is thrown by the Node.js runtime when a connection or HTTP
request is not closed properly after some time. You might encounter this error
from time to time if you configured a timeout on your
outgoing HTTP requests. The general solution to this issue is to catch the error
and repeat the request, preferably using an
exponential backoff
strategy so that a waiting period is added between subsequent retries until the
request eventually succeeds, or the maximum amount of retries is reached. If you
encounter this error frequently, try to investigate your request timeout
settings and choose a more appropriate value for the endpoint
if possible.

4. ECONNREFUSED

The ECONNREFUSED error is produced when a request is made to an endpoint but a
connection could not be established because the specified address wasn’t
reachable. This is usually caused by an inactive target service. For example,
the error below resulted from attempting to connect to http://localhost:8000
when no program is listening at that endpoint.

Error: connect ECONNREFUSED 127.0.0.1:8000
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
Emitted 'error' event on ClientRequest instance at:
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:526:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8000
}

The fix for this problem is to ensure that the target service is active and
accepting connections at the specified endpoint.

5. ERRADDRINUSE

This error is commonly encountered when starting or restarting a web server. It
indicates that the server is attempting to listen for connections at a port that
is already occupied by some other application.

Error: listen EADDRINUSE: address already in use :::3001
    at Server.setupListenHandle [as _listen2] (node:net:1330:16)
    at listenInCluster (node:net:1378:12)
    at Server.listen (node:net:1465:7)
    at Function.listen (/home/ayo/dev/demo/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:16:18)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 3001
}

The easiest fix for this error would be to configure your application to listen
on a different port (preferably by updating an environmental variable). However,
if you need that specific port that is in use, you can find out the process ID
of the application using it through the command below:

Output

COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    2902  ayo   19u  IPv6 781904      0t0  TCP *:3001 (LISTEN)

Afterward, kill the process by passing the PID value to the kill command:

After running the command above, the application will be forcefully closed
freeing up the desired port for your intended use.

6. EADDRNOTAVAIL

This error is similar to EADDRINUSE because it results from trying to run a
Node.js server at a specific port. It usually indicates a configuration issue
with your IP address, such as when you try to bind your server to a static IP:

const express = require('express');
const app = express();

const server = app.listen(3000, '192.168.0.101', function () {
  console.log('server listening at port 3000......');
});

Output

Error: listen EADDRNOTAVAIL: address not available 192.168.0.101:3000
    at Server.setupListenHandle [as _listen2] (node:net:1313:21)
    at listenInCluster (node:net:1378:12)
    at doListen (node:net:1516:7)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRNOTAVAIL',
  errno: -99,
  syscall: 'listen',
  address: '192.168.0.101',
  port: 3000
}

To resolve this issue, ensure that you have the right IP address (it may
sometimes change), or you can bind to any or all IPs by using 0.0.0.0 as shown
below:

var server = app.listen(3000, '0.0.0.0', function () {
  console.log('server listening at port 3000......');
});

7. ECONNABORTED

The ECONNABORTED exception is thrown when an active network connection is
aborted by the server before reading from the request body or writing to the
response body has completed. The example below demonstrates how this problem can
occur in a Node.js program:

const express = require('express');
const app = express();
const path = require('path');

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
  });
  res.end();
});

const server = app.listen(3000, () => {
  console.log('server listening at port 3001......');
});

Output

Error: Request aborted
    at onaborted (/home/ayo/dev/demo/node_modules/express/lib/response.js:1030:15)
    at Immediate._onImmediate (/home/ayo/dev/demo/node_modules/express/lib/response.js:1072:9)
    at processImmediate (node:internal/timers:466:21) {
  code: 'ECONNABORTED'
}

The problem here is that res.end() was called prematurely before
res.sendFile() has had a chance to complete due to the asynchronous nature of
the method. The solution here is to move res.end() into sendFile()‘s
callback function:

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
    res.end();
  });
});

8. EHOSTUNREACH

An EHOSTUNREACH exception indicates that a TCP connection failed because the
underlying protocol software found no route to the network or host. It can also
be triggered when traffic is blocked by a firewall or in response to information
received by intermediate gateways or switching nodes. If you encounter this
error, you may need to check your operating system’s routing tables or firewall
setup to fix the problem.

9. EAI_AGAIN

Node.js throws an EAI_AGAIN error when a temporary failure in domain name
resolution occurs. A DNS lookup timeout that usually indicates a problem with
your network connection or your proxy settings. You can get this error when
trying to install an npm package:

Output

npm ERR! code EAI_AGAIN
npm ERR! syscall getaddrinfo
npm ERR! errno EAI_AGAIN
npm ERR! request to https://registry.npmjs.org/nestjs failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org

If you’ve determined that your internet connection is working correctly, then
you should investigate your DNS resolver settings (/etc/resolv.conf) or your
/etc/hosts file to ensure it is set up correctly.

10. ENOENT

This error is a straightforward one. It means «Error No Entity» and is raised
when a specified path (file or directory) does not exist in the filesystem. It
is most commonly encountered when performing an operation with the fs module
or running a script that expects a specific directory structure.

fs.open('non-existent-file.txt', (err, fd) => {
  if (err) {
    console.log(err);
  }
});

Output

[Error: ENOENT: no such file or directory, open 'non-existent-file.txt'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'non-existent-file.txt'
}

To fix this error, you either need to create the expected directory structure or
change the path so that the script looks in the correct directory.

11. EISDIR

If you encounter this error, the operation that raised it expected a file
argument but was provided with a directory.

// config is actually a directory
fs.readFile('config', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}

Fixing this error involves correcting the provided path so that it leads to a
file instead.

12. ENOTDIR

This error is the inverse of EISDIR. It means a file argument was supplied
where a directory was expected. To avoid this error, ensure that the provided
path leads to a directory and not a file.

fs.opendir('/etc/passwd', (err, _dir) => {
  if (err) throw err;
});

Output

[Error: ENOTDIR: not a directory, opendir '/etc/passwd'] {
  errno: -20,
  code: 'ENOTDIR',
  syscall: 'opendir',
  path: '/etc/passwd'
}

13. EACCES

The EACCES error is often encountered when trying to access a file in a way
that is forbidden by its access permissions. You may also encounter this error
when you’re trying to install a global NPM package (depending on how you
installed Node.js and npm), or when you try to run a server on a port lower
than 1024.

fs.readFile('/etc/sudoers', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EACCES: permission denied, open '/etc/sudoers'] {
  errno: -13,
  code: 'EACCES',
  syscall: 'open',
  path: '/etc/sudoers'
}

Essentially, this error indicates that the user executing the script does not
have the required permission to access a resource. A quick fix is to prefix the
script execution command with sudo so that it is executed as root, but this is
a bad idea
for security reasons.

The correct fix for this error is to give the user executing the script the
required permissions to access the resource through the chown command on Linux
in the case of a file or directory.

sudo chown -R $(whoami) /path/to/directory

If you encounter an EACCES error when trying to listen on a port lower than
1024, you can use a higher port and set up port forwarding through iptables.
The following command forwards HTTP traffic going to port 80 to port 8080
(assuming your application is listening on port 8080):

sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

If you encounter EACCES errors when trying to install a global npm package,
it usually means that you installed the Node.js and npm versions found in your
system’s repositories. The recommended course of action is to uninstall those
versions and reinstall them through a Node environment manager like
NVM or Volta.

14. EEXIST

The EEXIST error is another filesystem error that is encountered whenever a
file or directory exists, but the attempted operation requires it not to exist.
For example, you will see this error when you attempt to create a directory that
already exists as shown below:

const fs = require('fs');

fs.mkdirSync('temp', (err) => {
  if (err) throw err;
});

Output

Error: EEXIST: file already exists, mkdir 'temp'
    at Object.mkdirSync (node:fs:1349:3)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:3:4)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  errno: -17,
  syscall: 'mkdir',
  code: 'EEXIST',
  path: 'temp'
}

The solution here is to check if the path exists through fs.existsSync()
before attempting to create it:

const fs = require('fs');

if (!fs.existsSync('temp')) {
  fs.mkdirSync('temp', (err) => {
    if (err) throw err;
  });
}

15. EPERM

The EPERM error may be encountered in various scenarios, usually when
installing an npm package. It indicates that the operation being carried out
could not be completed due to permission issues. This error often indicates that
a write was attempted to a file that is in a read-only state although you may
sometimes encounter an EACCES error instead.

Here are some possible fixes you can try if you run into this problem:

  1. Close all instances of your editor before rerunning the command (maybe some
    files were locked by the editor).
  2. Clean the npm cache with npm cache clean --force.
  3. Close or disable your Anti-virus software if have one.
  4. If you have a development server running, stop it before executing the
    installation command once again.
  5. Use the --force option as in npm install --force.
  6. Remove your node_modules folder with rm -rf node_modules and install them
    once again with npm install.

Conclusion

In this article, we covered 15 of the most common Node.js errors you are likely
to encounter when developing applications or utilizing Node.js-based tools, and
we discussed possible solutions to each one. This by no means an exhaustive list
so ensure to check out the
Node.js errors documentation or the
errno(3) man page for a
more comprehensive listing.

Thanks for reading, and happy coding!

Check Uptime, Ping, Ports, SSL and more.

Get Slack, SMS and phone incident alerts.

Easy on-call duty scheduling.

Create free status page on your domain.

Got an article suggestion?
Let us know

Share on Twitter

Share on Facebook

Share via e-mail

Next article

How to Configure Nginx as a Reverse Proxy for Node.js Applications

Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

➜  sample-simple-app git:(master) ✗ grunt
Running "connect:server:keepalive" (connect) task
Starting connect web server on localhost:9190.
Waiting forever...
Fatal error: listen EADDRNOTAVAIL

I am continually getting this error even when I change the port to 8000, 8080, 9001, etc. I have tried sudo killall node and I have run «ps aux | grep node» and I do not have any node processes running. I have also checked netstart and do not have anything running on those ports.

It appears that somehow grunt or connect is persisting this server? I have keepalive on there, but I usually terminate the process with Control + C. Yesterday, it would sometimes work and sometimes give me this error, but now I get it all the time.

Here’s the Gruntfile

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
      server: {
        options: {
          port: 9190,
          keepalive: false,
        }
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */n'
      },
      build: {
        src: 'src/<%= pkg.name %>.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    },
    jasmine: {
      test: {
        src: 'app/**/*.js',
        options: {
          specs: 'test/*.spec.js',
          helpers: 'test/*.helper.js',
          host: 'http://127.0.0.1:8080'
        }
      }
    }
  });

  // A basic server for testing the app - this server only runs while grunt is running. Use keepalive: true for use as a development server
  grunt.loadNpmTasks('grunt-contrib-connect');

  // Load the plugin for Jasmine bdd testing
  grunt.loadNpmTasks('grunt-contrib-jasmine');

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Default task(s).
  grunt.registerTask('default', ['connect:server:keepalive']);
  grunt.registerTask('test', ['connect:server', 'jasmine:test']);

};

I’m on Mac OSX Mountain Lion (UNIX) and I have node 0.8.15, grunt-cli v0.1.7, grunt v0.4.1.

8 ответов

У меня была эта проблема, и я думал, что это проблема портов, но она оказалась проблемой IP.

У меня была переменная окружения HOST, указывающая на статический IP-адрес, и мой сервер Node прослушивал этот адрес. В какой-то момент, когда мой маршрутизатор переработал, он начал присваивать моей машине новый IP-адрес, и я начал получать сообщение об ошибке. Это было исправлено путем изменения адреса, который прослушивал мой сервер.

Моя конфигурация:

app.set('port', process.env.PORT || 3000);
app.set('host', process.env.HOST || '0.0.0.0');

http.createServer(app).listen(app.get('port'), app.get('host'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

Убедитесь, что ваш хост поражает вашу машину. В любом случае, loopback, как предложил @miltonb, всегда должен работать:

app.set('host', '127.0.0.1');

JohnnyCoder
31 авг. 2013, в 15:15

Поделиться

Я получал ту же ошибку, а затем я сменил порт и работал

Federico
05 окт. 2012, в 01:47

Поделиться

Может ли быть, что node уже запускал сервер? Я получил аналогичную ошибку и нашел это при устранении неполадок. Завершение работы предыдущего сервера node решило мою проблему.

jonrh
05 авг. 2012, в 04:32

Поделиться

Я думаю, вам нужно немного больше контекста, как некоторые из вашего кода. Я предполагаю, что вы начинаете слушать веб-сервер или сокет? Основываясь на этом предположении, я получаю что-то подобное, когда я запускаю базовый веб-сервер на своем тестовом сервере, если я не запускаю локальный хост.

events.js:48
        throw arguments[1]; // Unhandled 'error' event
                   ^
Error: listen EADDRNOTAVAIL
    at errnoException (net.js:670:11)
    at Array.0 (net.js:756:28)
    at EventEmitter._tickCallback (node.js:190:38)

Попробуйте изменить параметр [hostname] на localhost:

var http = require('http');
http.createServer( function ).listen(8000, '127.0.0.1');

miltonb
06 июнь 2012, в 06:32

Поделиться

Для меня у меня была такая же ошибка, и когда я проверяю свою конфигурацию, я обнаружил, что host=127.0.0.0, которая вызывает ошибку, потому что она должна быть 127.0.0.1 вместо 127.0.0.0

Abdennour TOUMI
09 нояб. 2016, в 04:06

Поделиться

Это также произойдет, когда «ip addr add i: p: v: 6» все еще находится в подвешенном состоянии или что-то (только что выполненное /ing ), и интерфейс, я полагаю, не полностью готов слушать, добавляя новый адрес ipv6.

Спящий режим execSync в течение 2 секунд, похоже, позволяет прослушивать ошибку с ошибкой: прослушивать EADDRNOTAVAIL.

Это действительно ошибка, о которой я думаю в NodeJS 7.4.0 на Ubuntu, потому что этого не происходит с созданием адреса ipv4 в момент перед подключением/прослушиванием.

Master James
13 апр. 2017, в 07:31

Поделиться

var express = require('express');

var app = express();
app.set('port', process.env.PORT || 3000);
app.set('host', process.env.HOST || 'localhost');

app.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('host') + ':' + app.get('port'));
});

работает для меня.
он также является общим для отладки localhost и вашего локального ip без каких-либо изменений.

ofir_aghai
01 фев. 2016, в 22:27

Поделиться

В большинстве случаев это будет IP-адрес или имя хоста. Причина в том, что node js принимает это как ключевой элемент для запуска сервера. если есть конфликт или неверный IP-адрес, он записывается с этой ошибкой

Ошибка: прослушивание EADDRNOTAVAIL

надеюсь, что это поможет.

vinod babu
01 сен. 2014, в 06:43

Поделиться

Ещё вопросы

  • 0Div не будет 100% ширины браузера в IE8
  • 0Моя программа неожиданно завершается, когда я вызываю return в рекурсивной функции
  • 0Mongodb вставить в поддокументы
  • 0IE8 $ (‘body’). Width () = 0 при перерисовке
  • 0Платежи по кредитной карте Payeezy всегда получают сообщение об ошибке «Ошибка проверки HMAC»
  • 1Мои модули не могут быть найдены
  • 1Как изменить альфа шестнадцатеричного значения ARGB, используя целочисленные значения в Java
  • 0Защита Hotlink Facebook не получает изображения
  • 0ошибка: передача ‘const ComplexNumber’ в качестве ‘this’ аргумента ‘const ComplexNumber & ComplexNumber :: operator — = (const Complex)
  • 1WooCommerce Rest API Oauth с Javascript
  • 0Сортируемый не работает с вкладками
  • 0Y-ось углового NVD3 устанавливает минимальное значение данных в качестве максимального значения диапазона
  • 0SELECT… FOR UPDATE выбор старых данных после фиксации
  • 1MemoryError при использовании метода read () при чтении файла JSON большого размера из Amazon S3
  • 0использование ENUM в Visual Studio C ++
  • 1Получение пустых значений с использованием Javascript
  • 0Ошибка внутреннего соединения SQL с PHP PDO
  • 0Как получить последнюю созданную запись, используя петли api и angularjs
  • 0Изображения не отображаются в строке
  • 0Можно ли иметь, если еще в HTTP-запрос в угловых JS?
  • 1Низкоуровневый API Amazon S3 для загрузки больших файлов
  • 1Python — Как напечатать содержимое списка, в котором есть объекты класса?
  • 0Как хранить отсортированный набор целых чисел в двоичном файле?
  • 1Математика за камерой от третьего лица
  • 1Есть ли более чистый и эффективный способ сделать эти калькуляторы BMI & Fat% в Python?
  • 0Сохранение неизвестного количества целых чисел, не занимая слишком много времени / памяти
  • 1Отслеживание статистики Android Маркета
  • 0Как изменить стиль текста вкладки браузера с помощью Javascript?
  • 1Тензор потока: как работает gen_nn_ops.max_pool_grad_v2 ()?
  • 1первый андроид сервис
  • 0MySQL: слияние таблиц отношений один к одному
  • 1Клавиши со стрелками, TextField фокус в Java?
  • 13D-картографирование структуры данных в Гуаве
  • 1Откройте Winword от C # в защищенном режиме
  • 1Почему concurrent.futures.ThreadPoolExecutor (). Submit не возвращается немедленно?
  • 1Как получить Alertdialog с фоном не в фокусе (нечеткий)
  • 0Прокрутите назад до позиции DIV из JS / Jquery
  • 1Как использовать сервис REST со сложным типом в C #?
  • 1Открытый плагин NetBeans и OpenOffice
  • 1Строка в Integer не работает
  • 0Не могу установить zfc-user с zfc-user-doctrine-mongo-odm
  • 1выпадающий элемент не может быть выбран с помощью Selenium Java с PageFactory
  • 1Что может быть более быстрым способом генерации матрицы, в которой хотя бы один элемент ненулевой в строке?
  • 0Как добавить полосу прокрутки в контейнер перетаскивания с AngularJS?
  • 1getCurrentPosition lat / lng не переводит на правильную позицию в Google Maps
  • 0Ошибка типа: не удается прочитать свойство ‘0’ неопределенного AngularJS
  • 1Добавить собственный стиль карты в Mapbox.js
  • 1Получение пути и порта сервера Apache Tomcat динамически
  • 0Не уверен, почему этот код JQuery не будет работать
  • 1Ява получить открытый текст в RSA от расшифровки

I am using ESP8266 web server to control GPIO. My Wi-Fi network give it an IP of ….99:3300

And it works…THEN I decided to use node.js ( I am a beginner ) and here it is

const http = require(‘http’);

const hostname = ‘192.168.1.99’;

const port = 3300;

const server = http.createServer((req, res) => {

res.statusCode = 200;

res.setHeader(‘Content-Type’, ‘text/plain’);

res.end(‘/5/on’);

});

server.listen(port, hostname, () => {

console.log(`Server running at http://${hostname}:${port}/`);

});

It does not work…

Error: listen EADDRNOTAVAIL: address not available 192.168.1.99:3300

[90m at Server.setupListenHandle [as _listen2] (net.js:1296:21)[39m

[90m at listenInCluster (net.js:1361:12)[39m

[90m at doListen (net.js:1500:7)[39m

[90m at processTicksAndRejections (internal/process/task_queues.js:85:21)[39m

Emitted ‘error’ event on Server instance at:

[90m at emitErrorNT (net.js:1340:8)[39m

[90m at processTicksAndRejections (internal/process/task_queues.js:84:21)[39m {

code: [32m’EADDRNOTAVAIL'[39m,

errno: [32m’EADDRNOTAVAIL'[39m,

syscall: [32m’listen'[39m,

address: [32m’192.168.1.99′[39m,

port: [33m3300[39m

}

my url request gpio 5 to be on ( /5/on) and it is working on the server created by ESP8266

Понравилась статья? Поделить с друзьями:
  • Error listen eaddrinuse code eaddrinuse errno eaddrinuse syscall listen
  • Error listen eaddrinuse address already in use 8081
  • Error listen eaddrinuse address already in use 8080
  • Error listen eaddrinuse address already in use 51826
  • Error listen eaddrinuse address already in use 5000