1

Проблема

Если я делаю запрос на сервер из getInitialProps получаю ответ:

FetchError: request to http://localhost:8081/api/brand failed, reason: connect ECONNREFUSED 127.0.0.1:8081

at ClientRequest.<anonymous> (/app/node_modules/node-fetch/lib/index.js:1461:11)

at ClientRequest.emit (events.js:315:20)

at Socket.socketErrorListener (_http_client.js:469:9)

at Socket.emit (events.js:315:20)

at emitErrorNT (internal/streams/destroy.js:106:8)

at emitErrorCloseNT (internal/streams/destroy.js:74:3)

at processTicksAndRejections (internal/process/task_queues.js:80:21) {

type: 'system',

errno: 'ECONNREFUSED',

code: 'ECONNREFUSED'

}

Пример кода (запрос падает с ошибкой)

MyApp.getInitialProps = async (appContext) => {

  fetch('http://localhost:8081/api/brand')
    .then(e => {
      console.log(e);
    })
    .catch(e => {
      console.log(e);
    });

  return {};
};

Но если я делаю этот же запрос из компоненты, например из useEffect запрос проходит, или из postman, или из консоли получаю ответ 200 с данными.

Пример кода (запрос проходит и ответ 200)

import { useEffect } from 'react';

const Admin = () => {
  useEffect(() => {
    fetch('http://localhost:8081/api/brand')
      .then(e => {
        console.log(e.json());
      })
      .catch(e => {
        console.log(e);
      });
  }, []);
  return (
    <div>
      Lorem ipsum
    </div>
  );
};

export default Admin;

Запуск докера

docker-compose.yml:

version: '3.8'

services:
  api:
    restart: always
    ports:
      - 8081:8081
    build:
      context: ./server
      dockerfile: ./Dockerfile
    command: npm run dev
    volumes:
      - ./server:/app/server
    depends_on:
      - mongo

  frontend:
    restart: always
    ports:
      - 3000:3000
    build:
      context: ./
      dockerfile: ./Dockerfile
    volumes:
      - ./:/app/
    depends_on:
      - api

  mongo:
    image: mongo
    expose:
      - 27017
    ports:
      - 27017:27017
    volumes:
      - apiDB:/data/db

volumes:
  apiDB:

logs client:

> [email protected] dev /app

> next dev


ready - started server on 0.0.0.0:3000, url: http://localhost:3000

info - Using external babel configuration from /app/.babelrc

event - compiled successfully

event - build page: /admin

wait - compiling...

event - compiled successfully

logs server

> [email protected] dev /app/server

> kill-port 1111 && nodemon src/app.js


Process on port 1111 killed

[nodemon] 2.0.7

[nodemon] to restart at any time, enter `rs`

[nodemon] watching path(s): *.*

[nodemon] watching extensions: js,mjs,json

[nodemon] starting `node src/app.js`

(node:56) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

(Use `node --trace-deprecation ...` to show where the warning was created)

(node:56) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

Server is up and running on port number 8081

Connection Succeeded

Вопрос: Почему один и тот-же запрос к одному и тому-же серверу падает в getInitialProps?

2
  • Ну так первый явно происходит из ноды. Видимо в этот момент приложение ещё не запущено
    – Alexey Ten
    7 фев 2021 в 8:23
  • К тому же он происходит изнутри контейнера в котором 127.0.0.1 это этот же контейнер, а не контейнер с api
    – Alexey Ten
    7 фев 2021 в 8:27

1 ответ 1

0

Чтобы обратиться к api нужно изменить запрос в getInitialProps с http://localhost:8081/ на http://api:8081/

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.