我有2个微服务:带有next.js的前端和带有node.js的后端,我可以从前端通过REST-API从中获取数据。

我现在遇到的问题是,我的2个服务似乎并没有直接相互通信,事实是,当我使用fetch-API的getinitialProps()方法在开始时获取数据时,它就可以工作。我的服务器端前端通过服务名称找到后端。但是,当我从客户端到后端进行http请求时(例如通过浏览器表单输入)。它找不到后端了吗?这是为什么?

这是我的docker-compose.yml:

version: '3'

services:
  dcbackend:
    container_name: dcbackend
    build:
      context: ./dcbackend
      dockerfile: Dockerfile
    image: dcbackend
    hostname: dcbackend
    ports:
      - '7766:7766'

  dcfrontend:
    container_name: dcfrontend
    build:
      context: ./dcfrontend
      dockerfile: Dockerfile
    image: dcfrontend
    volumes:
      - /app/node_modules
      - ./dcfrontend:/app
    hostname: dcfrontend
    ports:
      - '6677:6677'

这是我的浏览器-客户端方法之一,用于将数据发送到后端(通过浏览器,我的网址是http:dcbackend ...,因此通常它应该找到后端所在的其他docker环境,但事实并非如此。) 。
    if (environment == 'dev') {
  url_link = `http://localhost:${port}`;
} else {
  url_link = `http://dcbackend:${port}`;
}

let doublettenListe_link = `${url_link}/doubletten/`;

 finishDocumentHandler = (anzeige,index) => {
    let thisDocumentID = anzeige.id;
    const requestOptions = {
        method: 'PUT'
    };

    fetch(doublettenListe_link + thisDocumentID, requestOptions)
    .then((response) => {
        this.setState({finishSuccess: 'Dubletten in Datenbank eintragen erfolgreich!'});
        this.setState({finishFail: ''});
        this.processDocumentArray(index);
        console.log(response);
    })
    .catch((error) => {
        this.setState({finishSuccess: ''});
        this.setState({finishFail : `Error beim Erzeugen des Eintrags! Eintrag wurde nicht in Datenbank gespeichert. Bitte prüfen, ob der Server läuft. ${error}`});
    });
  }

我的请求来自“网络”标签的响应是:
Request URL: http://dcbackend:7766/doubletten/304699981
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Access-Control-Request-Method: PUT
Origin: http://localhost:6677
Referer: http://localhost:6677/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36

它与docker-configuration或CORS()或其他有关吗?我无法执行客户端http请求到后端,但是,从后端进行初始获取以获取一些数据有效...

最佳答案

您必须将服务器端请求和客户端请求分开。您需要将主机地址用于客户端请求(例如http://localhost:7766),因为您的浏览器将无法通过docker别名访问后端。

您可以使用next.config.js定义仅服务器和公共(public)运行时配置。

例如:

// next.config.js
module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    apiUrl: 'http://dcbackend:7766'
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    apiUrl: 'http://localhost:7766'
  }
}

然后您需要使用apiUrl从nextjs获取getConfig()
// pages/index.js
import getConfig from 'next/config';

const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();

const apiUrl = serverRuntimeConfig.apiUrl || publicRuntimeConfig.apiUrl;

const Index = ({ json }) => <div>Index</div>;

Index.getInitialProps = async () => {
    try {
       const res = await fetch(`${apiUrl}/doubletten/304699981`);
       const json = await res.json();
       return { json };
    } catch(e) {
       console.log('Failed to fetch', e);
       return { json: null };
    }
}

export default Index;

10-07 17:38