【问题标题】:Routing in Serverless nuxt app not working无服务器 nuxt 应用程序中的路由不起作用
【发布时间】:2021-05-17 04:57:11
【问题描述】:

因此,每当我将 nuxt ssr 与无服务器一起使用时,都会遇到路由问题。当我使用部署到 AWS lambda 或使用 serverless-offline 时,它会生成前缀为 /{stage} 的 url,但 nuxt 似乎无法处理此问题,并且会引发 403、404 或 500 错误,因为到静态文件的路由不是以/{stage}为前缀。

我尝试在构建时将{stage} 添加到公共路径,结果为404,因为现在静态文件路径需要以另一个/{stage} 为前缀。如果我直接去{stage}/{stage}/_nuxt/{file} 就可以了。

build: {
    publicPath: '/{stage}/_nuxt'
}

所以环顾四周,我发现我可以将路由器基础更新到下面

router: {
   base: '/{stage}'
}

但现在该文件仅在其 {stage}/{stage}/{stage}/_nuxt/{file} 并删除上面的 publicPath 代码也不能使其工作时才加载。

这是针对静态文件的,当涉及到设置在“/”的主页的实际路由时,它们可以工作,但任何其他页面都不能工作,因为它们的 nuxt-links 没有以 /{stage} 为前缀或者,如果我将前缀添加到基础,当我访问 /{stage} 时会收到 Cannot GET / 错误。

我尝试了许多不同的方法,例如使用express,但是我没有运气,我在网上找到的任何教程都至少有 2 年的历史,而且 github 存储库也有同样的问题。我在 * 上找到的与我所拥有的有点相似的最接近的东西是 here,但这是针对静态网站的。

有人有什么想法吗?以下是serverless.yamlhandler.jsnuxt.jsnuxt.config.js 的代码。

Github Repo

serverless.yaml

service: nuxt-ssr-lambda

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${env:STAGE}
  region: eu-west-1
  lambdaHashingVersion: 20201221
  environment: 
    NODE_ENV: ${env:STAGE}
  apiGateway:
    shouldStartNameWithService: true

functions:
  nuxt:
    handler: handler.nuxt
    events:
      - http: ANY /
      - http: ANY /{proxy+}

plugins: 
  - serverless-apigw-binary
  - serverless-dotenv-plugin
  - serverless-offline

custom:
  apigwBinary:
    types:
      - '*/*'

handler.js

const sls = require('serverless-http')
const binaryMimeTypes = require('./binaryMimeTypes')
const nuxt = require('./nuxt')

module.exports.nuxt = sls(nuxt, {
    binary: binaryMimeTypes
})

nuxt.js

const { Nuxt } = require('nuxt')

const config = require('./nuxt.config.js')

const nuxt = new Nuxt({ ...config, dev: false })

module.exports = (req, res) =>
    nuxt.ready().then(() => nuxt.server.app(req, res))

nuxt.config.js

module.exports = {
  telemetry: false,

  head: {
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  css: [
  ],

  plugins: [
  ],

  components: true,

  buildModules: [
    '@nuxtjs/tailwindcss',
  ],

  modules: [
  ],

  router: {
    base: '/prod'
  },

  build: {
  }
}

【问题讨论】:

    标签: aws-lambda nuxt.js serverless-framework


    【解决方案1】:

    你是把它当作

        <p>Path: {{ $route.path }}</p>
        <NuxtLink to="/">Back to Mountains</NuxtLink>
    

    如果Yes 那么它应该可以工作,否则尝试使用redirect('/{stage}/_nuxt')

    对于 if 声明,将其放入 else 中,我认为它应该可以工作。

    【讨论】:

    • 我让 nuxt 为我生成路线,所以它会自动添加舞台。问题是当我在 AWS 中访问它时,访问它的路径是 {stage}/{stage}/_nuxt
    • 我认为在这种情况下,您需要使用标志或条件解析正确的路径。