Docker-compose make 2 microservices (frontend+backend) communicate to each other with http requests

前端 未结 1 499
情话喂你
情话喂你 2021-01-06 16:23

I have 2 microservices: frontend with next.js and a backend with node.js from where I fetch data via REST-APIs from the frontend.

I now have the problem, that my 2 s

相关标签:
1条回答
  • 2021-01-06 16:41

    You have to separate the server side and the client side requests. You need to use your host address for the client side requests (eg. http://localhost:7766), because your browser will not be able to reach the backend via docker alias.

    You can define the server-only and public runtime config with next.config.js.

    For example:

    // 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'
      }
    }
    

    Then you need get the apiUrl from nextjs with 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;
    
    0 讨论(0)
提交回复
热议问题