@zzz93

Почему не отвечает localhost при работе в node.js?

import { Server } from 'http';
const s = Server();
s.addListener('request', function (req, res) {
	res.end('My first server!\n');
});
s.listen(4321);

При набирании команды node . ответ:
events.js:377
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::4321
    at Server.setupListenHandle [as _listen2] (net.js:1331:16)
    at listenInCluster (net.js:1379:12)
    at Server.listen (net.js:1465:7)
    at file:///first_node/index.js:6:3
    at ModuleJob.run (internal/modules/esm/module_job.js:183:25)
    at async Loader.import (internal/modules/esm/loader.js:178:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)
    at async handleMainPromise (internal/modules/run_main.js:59:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1358:8)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 4321
}

Делаю другой порт(4320), при вызове команды curl localhost:4320 ответа нет(curl: (7) Failed to connect to 127.0.0.1 port 4320: Connection refused). В браузере соединение не устанавливается.
+ нет ответа от сервера в терминале при вызове команды curl localhost:4320/index.js -I
Что нужно сделать?
  • Вопрос задан
  • 397 просмотров
Пригласить эксперта
Ответы на вопрос 1
vool
@vool
Разработчик
const express = require('express');
const app = express();
exports.app = app;
const http = require('http');
const server = http.createServer(app);
app.get("/hello", (req, res) => {
    //либо перенапрвление на сайт:
   res.redirect("https://....");
   //либо отдать свою страницу(файл):
   res.sendFile(__dirname + '/public/index.html');
   //или отправить напрямую html-код:
   res.send(`
      <html>
         <head>
            <title>Server</title>
         </head>
         <body>
            <h1>hello server</h1>
         </body>
      </html>
   `);
})
server.listen(8080, () => {
    //console.log("\x1B[32m%c started", 'color: pink; background: red;');
});

А потом перейди в браузер по порту 8080 и в url добавь в конец /hello

63a9d0141008e516980901.png

Либо просто измени свой код на:

const { Server } = require('http');
const s = Server();
s.addListener('request', function (req, res) {
  res.end('My first server!\n');
});
s.listen(4321);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы