Nuxt.js SSR,其中将Nest API部署到Docker容器中的AWS上

问题描述 投票:0回答:1

我已经在此主题上尝试了大约500万种变体,并且花了大量时间浏览Nuxt文档,当将Nest后端部署到AWS的Docker容器中时,我无法获得带有Nest后端的Nuxt SSR。以下是我当前的设置。如果我遗漏了任何东西,请告诉我。

这是我遇到的错误:

https://www.noticeeverythingcreative.com/contact此路由以组件的POST方法向https://www.noticeeverythingcreative.com/api/contact/meta发出页面元数据的asyncData请求。这会产生来自Axios的大错误。以下是我认为相关的部分,但是如果您需要更多,请告诉我。

{
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: 'xxx.xx.x.x', // IP Address of the docker container
  port: 443,
  config: {
    url: 'https://www.noticeeverythingcreative.com/api/contact/meta',
    method: 'post',
    headers: {
      Accept: 'application/json, text/plain, */*',
      connection: 'close',
      'x-real-ip': 'xx.xxx.xxx.xxx', // My IP
      'x-forwarded-for': 'xx.xxx.xxx.xxx', // My IP
      'x-forwarded-proto': 'https',
      'x-forwarded-ssl': 'on',
      'x-forwarded-port': '443',
      pragma: 'no-cache',
      'cache-control': 'no-cache',
      'upgrade-insecure-requests': '1',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
      'sec-fetch-user': '?1',
      'sec-fetch-site': 'same-origin',
      'sec-fetch-mode': 'navigate',
      'accept-encoding': 'gzip, deflate',
      'accept-language': 'en-US,en;q=0.9',
      'Content-Type': 'application/json'
    },
    baseURL: 'https://www.noticeeverythingcreative.com'
  }

这是我的nuxt.config.js的相关部分:

mode: 'universal',
srcDir: './src',
rootDir: './',
modules: ['@nuxtjs/axios'],
// NOTE: I get the same errors if I leave this block out
server: {
    host: '0.0.0.0',
    port: 3002
},

[部署时,我使用Dockerfile将所有需要的文件从我的项目目录复制到容器中,运行yarn install,暴露端口3002,运行yarn build.prod,最后以CMD ["yarn", "start"]结尾(相关内容请参见下文) package.json脚本)。

"scripts": {
    "clean.nuxt": "rimraf .nuxt",
    "build.client": "nuxt build",
    "build.server": "tsc -p tsconfig.server.json", // Transpile TypeScript from `src/server` into `.nuxt/api`
    "build.prod": "run-s clean.nuxt build.client build.server",
    "start": "cross-env NODE_ENV=production node .nuxt/api/index.js",
}

docker镜像在本地构建,并推送到ECR存储库。然后,我通过SSH进入服务器并使用此撰写文件运行docker-compose up -d

version: '3.2'

services:
  my_service:
  image: link/to/my/image:${TAG:-prod}
  container_name: my_container
  hostname: www.noticeeverythingcreative.com
  restart: unless-stopped

ports:
  # Http Port
  - 3002:3002

networks:
  - web-network # External (the actual compose file also has the corresponding networks block at the bottom)

environment:
  - NODE_ENV=production
  - API_URL=https://www.noticeeverythingcreative.com
  - HOST=www.noticeeverythingcreative.com
  - PORT=3002
  - VIRTUAL_PORT=3002 

这是我的服务器端控制器,用于处理Nuxt渲染:

src / server / app / nuxt.controller.ts

import { Controller, Get, Request, Response } from '@nestjs/common';
import { join, resolve } from 'path';
import * as config from 'config';

const { Builder, Nuxt } = require('nuxt');
const nuxtConfig = require(join(resolve(), 'nuxt.config.js'));

@Controller()
export class NuxtController
{
    nuxt:any;

    constructor()
    {
        this.nuxt = new Nuxt(nuxtConfig);
        const Env = config as any;

        // Build only in dev mode
        if (Env.name === 'development')
        {
            const builder = new Builder(this.nuxt);
            builder.build();
        }
        else
        {
            this.nuxt.ready();
        }

    }

    @Get('*')
    async root(@Request() req:any, @Response() res:any)
    {
        if (this.nuxt)
        {
            return await this.nuxt.render(req, res);
        }
        else
        {
            res.send('Nuxt is disabled.');
        }
    }
}

这里是客户端联系人组件的asyncDatahead实现:

async asyncData(ctx:any)
{
    // fetch page meta from API
    try
    {
        const meta = await ctx.$axios(<any>{
            method: 'post',
            url: `${ ctx.env.apiHost }/contact/meta`,
            headers: { 'Content-Type': 'application/json' }
        });

        return { meta: meta.data };
    }
    catch (error)
    {
        // Redirect to error page or 404 depending on server response
        console.log('ERR: ', error);
    }
}

head()
{
    return this.$data.meta;
}

我遇到的问题仅发生在生产主机上的生产环境中。我可以在本地运行yarn build.prod && cross-env NODE_ENV=development node .nuxt/api/index.js,并且该应用程序可以正常运行和呈现。

更新

如果我允许Nuxt应用程序实际在docker容器内的localhost上运行,则会遇到相反的问题。例如,如果我将nuxt.config.js服务器和axios块更改为

server: {
    port: 3002, // default: 3000,
},
axios: {
    baseURL: 'http://localhost:3002'
}

并将请求更改为:

const meta = await ctx.$axios(<any>{
    method: 'post',
    // NOTE: relative path here instead of the absolute path above
    url: `/api/contact/meta`,
    headers: { 'Content-Type': 'application/json' }
});

return { meta: meta.data };

https://www.noticeeverythingcreative.com/contact的新负载会很好。可以通过查看页面源代码并查看标题已更新并且没有控制台错误来确认。但是,如果您加载主页(https://www.noticeeverythingcreative.com)并单击导航栏中的联系人链接,则会看到POST http://localhost:3002/api/contact/meta net::ERR_CONNECTION_REFUSED

注意:这是自该问题的最后编辑起所部署的版本。

docker axios nuxt.js nestjs
1个回答
0
投票

我想出了一个解决方案,但我不喜欢它,因此,如果有人有更好的建议,请发表。

© www.soinside.com 2019 - 2024. All rights reserved.