You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何每24小时重新生成Nuxt动态站点地图?node-cron尝试失败

动态站点地图定期重新生成解决方案

你当前的问题在于:构建时生成的站点地图是静态文件,generated钩子中的cron仅在构建阶段执行一次;若为静态部署,构建完成后进程不会持续运行,定时任务自然无法生效。要实现动态内容的定期更新,需切换为运行时动态生成的思路,以下是可行方案:


方案一:Server API手动生成+定时任务

1. 创建站点地图生成API

在server/api/sitemap-generate.js中编写生成逻辑,手动调用sitemap模块生成并写入静态文件:

import { createSitemap } from '@nuxtjs/sitemap'
import axios from 'axios'
import { writeFile } from 'fs/promises'

export default defineEventHandler(async () => {
  // 生成法语站点地图(获取最新动态路由)
  const frRoutes = await axios.get('http://localhost:8080/fr/article/active')
    .then(res => res.data?.body?.map(article => `/fr/actualite/article?titre=${article.article.url}`))

  const sitemapFr = await createSitemap({
    hostname: 'https://test.fr',
    path: '/sitemap-fr.xml',
    exclude: ['/*', '/it/**', '/es/**'],
    routes: frRoutes
  })
  await writeFile('./public/sitemap-fr.xml', sitemapFr.toString())

  // 生成西班牙语站点地图
  const sitemapEs = await createSitemap({
    hostname: 'https://test.es',
    path: '/sitemap-es.xml',
    exclude: ['/*', '/it/**', '/fr/**']
  })
  await writeFile('./public/sitemap-es.xml', sitemapEs.toString())

  // 生成意大利语站点地图
  const sitemapIt = await createSitemap({
    hostname: 'https://test.it',
    path: '/sitemap-it.xml',
    exclude: ['/*', '/fr/**', '/es/**']
  })
  await writeFile('./public/sitemap-it.xml', sitemapIt.toString())

  return { status: 'success', message: '站点地图已更新' }
})

2. 启动时添加定时任务

修改nuxt.config.js,在服务启动时注册cron定时任务,每24小时触发一次API更新:

import cron from 'node-cron'
import axios from 'axios'

export default defineNuxtConfig({
  // 原有配置保留,调整sitemap的routes为运行时动态获取
  sitemap: {
    path: '/sitemap.xml',
    sitemaps: [
      {
        hostname: 'https://test.fr',
        path: '/sitemap-fr.xml',
        exclude: ['/*', '/it/**', '/es/**'],
        routes: async () => {
          return await axios.get('http://localhost:8080/fr/article/active')
            .then(res => res.data?.body?.map(article => `/fr/actualite/article?titre=${article.article.url}`))
        }
      },
      {
        hostname: 'https://test.es',
        path: '/sitemap-es.xml',
        exclude: ['/*', '/it/**', '/fr/**']
      },
      {
        hostname: 'https://test.it',
        path: '/sitemap-it.xml',
        exclude: ['/*', '/fr/**', '/es/**']
      }
    ]
  },
  hooks: {
    'server:start': () => {
      // cron表达式:0 0 * * * 表示每天凌晨0点执行一次
      cron.schedule('0 0 * * *', async () => {
        console.log('开始更新站点地图...')
        try {
          await axios.get('http://localhost:3000/api/sitemap-generate')
          console.log('站点地图更新完成')
        } catch (err) {
          console.error('站点地图更新失败:', err)
        }
      })
    }
  }
})

方案二:SSR模式下利用动态路由自动更新

如果你的项目是SSR部署,无需额外定时任务——只需确保sitemap.routes配置为异步获取最新数据,每次访问sitemap.xml时模块都会动态生成最新内容,自然实现实时更新。


关键注意事项

  • 若为静态部署(如Vercel、Netlify),不能依赖Nuxt进程内的cron,需使用平台自带的定时任务功能(如Vercel Cron Jobs)触发API更新。
  • 确保部署环境对public目录有写入权限,或根据实际路径调整文件写入位置。

内容的提问来源于stack exchange,提问作者EleXorZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:35:21