首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Nuxt.js:在某些动态路由上生产的404代码

Nuxt.js:在某些动态路由上生产的404代码
EN

Stack Overflow用户
提问于 2022-09-20 11:40:51
回答 1查看 412关注 0票数 0

我的Nuxt项目有大约700-1000个静态和动态页面,通过Netlify托管。其中300条是正确生成的。

在生产中,我发现某些动态生成的路由获得了HTTP 404状态代码。但是,它们是生成和加载的,在生产中没有任何其他错误。他们只是得到404错误代码,这对SEO有坏的影响。Dev服务器和通过本地dist运行生成的nuxt start文件夹都没有显示这些页面上的404代码。静态生成的页面工作正常。

以下是我对nuxt.config.js的设置(请参阅下面的完整列表)

代码语言:javascript
运行
复制
  target: 'static',

  generate: {
    fallback: true, 
    ....
  }

由于纽特履带机,我没有在generate()上指定动态路由。

package.json:

代码语言:javascript
运行
复制
{
  "name": "xxxxxxx",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "generate_coin_list_file": "node scripts/generate_coin_list.js",
    "generate_coin_images": "node scripts/download_coin_images.js"
  },
  "dependencies": {
    "@nuxt/content": "^1.14.0",
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/gtm": "^2.4.0",
    "@nuxtjs/proxy": "^2.1.0",
    "@nuxtjs/sitemap": "^2.4.0",
    "core-js": "^3.15.1",
    "frontmatter-markdown-loader": "^3.7.0",
    "ipx": "^0.9.4",
    "lite-youtube-embed": "^0.2.0",
    "nuxt": "^2.15.8",
    "nuxt-jsonld": "^1.5.3",
    "v-click-outside": "^3.2.0",
    "vue-disqus": "^4.0.1"
  },
  "devDependencies": {
    "@nuxt/image": "^0.6.2",
    "@nuxtjs/tailwindcss": "^4.2.0",
    "eslint-config-prettier": "^8.3.0",
    "postcss": "^8.3.5",
    "prettier": "^2.3.2"
  }
}

我不知道该在哪里查找,因为这个错误似乎没有遵循模式。因为我可以在本地生成它而没有错误,所以Netlify可能会出现问题。你们觉得这个怎么样?谢谢!

示例: _slug.vue

代码语言:javascript
运行
复制
export default {
  name: 'BlogSlug',
  async asyncData({ $content, params, route, error }) {
    let author = {}

    let article = await $content('articles', { deep: true })
      .where({
        slug: params.slug,
      })
      .fetch()
      .catch(() => {
        error({ statusCode: 404, message: 'Page not found' })
      })

    article = article[0]

    const allArticles = await $content('articles', {
      deep: true,
    })
      .sortBy('date', 'desc')
      .limit(6)
      .fetch()
      .catch(() => {
        error({ statusCode: 404, message: 'Page not found' })
      })

    if (article.author) {
      author = await $content('authors')
        .where({
          id: article.author,
        })
        .fetch()
        .catch(() => {
          error({ statusCode: 404, message: 'Page not found' })
        })
    }
    return { article, allArticles, author }
  },
...
}

nuxt.config.js

代码语言:javascript
运行
复制
import coinList from './data/coin_list.json'

export default {
  target: 'static',

  head: {
    title: 'XXXXXX',
    htmlAttrs: {
      lang: 'de',
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' },
      {
        hid: 'twitter:card',
        property: 'twitter:card',
        content: 'summary_large_image',
      },
    ],
    link: [
      {
        hid: 'apple-touch-icon',
        rel: 'apple-touch-icon',
        sizes: '180x180',
        href: '/favicon.ico',
      },
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
    ],
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
    '~/assets/css/tailwind.css',
    'node_modules/lite-youtube-embed/src/lite-yt-embed.css',
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    '~/plugins/metadata',
    '~/plugins/youtube.client.js',
    '~/plugins/jsonLd.js',
    { src: '@/plugins/vClickOutside', ssr: false },
    '~/plugins/disqus',
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: [
    '~/components',

    { path: '~/components/utils', extensions: ['vue'] },
    { path: '~/components/global' },
  ],

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/tailwindcss
    '@nuxtjs/tailwindcss',
    [
      '@nuxt/image',
      {
        provider: 'static',
      },
    ],
    '@/modules/sitemapRouteGenerator.js',
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    '@nuxtjs/axios',
    '@nuxt/content',
    '@nuxtjs/proxy',
    '@nuxtjs/gtm',
    // has to be last
    '@nuxtjs/sitemap',
  ],

  sitemap: {
    hostname: process.env.NUXT_ENV_BASE_URL,
    path: '/sitemap.xml',
  },

  // GTM Analytics
  gtm: {
    enabled: true,
    pageTracking: true,
  },

  axios: {},

  image: {
    // Options
    domains: ['assets.coingecko.com', 'coingecko.com'],
    presets: {
      blog: {
        modifiers: {
          format: 'webp',
        },
      },
    },
  },

  // Content module configuration: https://go.nuxtjs.dev/config-content
  content: {
    // nestedProperties: ['articles.slug'],
  },

  generate: {
    fallback: true,
    async routes() {
      const routes = await _getRoutes()

      async function _getRoutes($content) {
        const paths = []

        coinList.forEach((coin) => {
          paths.push({
            route: `/coins/${coin.id}/historisch/`,
            payload: coin.id,
          })
        })

        return paths
      }

      return routes
    },
  },

  router: {
    routeNameSplitter: '/',
  },

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    extend(config) {
      config.module.rules.push({
        test: /\.md$/,
        loader: 'frontmatter-markdown-loader',
      })
    },
  },
}

模块: sitemapRouteGenerator.js

代码语言:javascript
运行
复制
export default function () {
  this.nuxt.hook('generate:done', (context) => {
    const routesToExclude = /\/index|\/articles\/|\/undefined/ // Add any route you don't want in your sitemap. Potentially get this from an .env file.
    const allRoutes = Array.from(context.generatedRoutes)
    // console.log(context.generatedRoutes)

    const routes = allRoutes.filter((route) => !routesToExclude.test(route))

    // console.log(routes)

    this.nuxt.options.sitemap.routes = [...routes]
  })
}
EN

回答 1

Stack Overflow用户

发布于 2022-09-20 16:56:16

我解决了这个问题。修复是在生成钩子中生成所有动态页面的路由,即使Nuxt状态是关于生成爬行器的。

代码语言:javascript
运行
复制
Since Nuxt 2.14+, nuxt generate has a crawler feature integrated which will crawl all your links and generate your routes based on those links. Therefore you do not need to do anything in order for your dynamic routes to be crawled.

我猜它只在静态页面上工作,部分在动态路径(?)上工作。由于我使用了嵌套的目录结构,所以在手动修改路由路径之前必须进行修改。

代码语言:javascript
运行
复制
  generate: {
    fallback: true,
    async routes() {
      let routes
      const contentRoutes = await _getContentRoutes()

      async function _getContentRoutes() {
        const { $content } = require('@nuxt/content')
        const files = await $content({ deep: true }).only(['path']).fetch()
        return files.map((file) => file.path.replace('/articles/', ''))
      }

      return routes
    },
  },

在这个例子中,我在内容/文章/SOMEARTICLE.md中有一些标记文件,所以我不得不从路径中删除‘/文章’。否则,nuxt在生成路由时会抛出一个错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73786118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档