简体   繁体   English

从多个数据源构建 Nuxt 站点地图

[英]Building Nuxt sitemap from multiple data sources

I'm working with Nuxt in SSR mode and want to build out a dynamic sitemap for multiple routes/ data sets.我正在 SSR 模式下使用 Nuxt,并希望为多个路线/数据集构建动态站点地图。

The issue I'm facing now is that the async/ await function only allows 'data' as the variable.我现在面临的问题是 async/await 函数只允许“数据”作为变量。 The same function with 'post' as the variable leads to a "map function does not exist"与 'post' 相同的函数作为变量导致“地图函数不存在”

This is what's in my Nuxt.config.js file这是我的 Nuxt.config.js 文件中的内容

  sitemap: {
    hostname: "https://example.com",
    routes: async () => {
      let { data } = await axios.get('https://api.example.com/api/v1/locations');
      data = data.data.map((loc) => `/locations/${loc.slug}`);
      console.log(data);

      let { posts } = await axios.get('https://cms.example.com/wp-json/wp/v2/posts');
      posts = posts.map((post) => `/posts/${post.slug}`);
      console.log(posts);

      data.concat(posts);

      return data
    },
    path: '/sitemap.xml'
  }

The resulting output I'm looking for should be formatted like this:我正在寻找的结果输出的格式应如下所示:

[
  '/locations/location-one',
  '/locations/location-two',
  '/locations/location-three',
  '/posts/post-one',
  '/posts/post-two',
  '/posts/post-three',
]

The error I'm getting:我得到的错误:

Cannot read property 'map' of undefined

and it's occuring on this line:它发生在这条线上:

posts = posts.map((post) => `/posts/${post.slug}`)

so it appears to me that it's not accepting 'posts' as a valid variable for its own await function.所以在我看来,它不接受“posts”作为其自己的 await 函数的有效变量。

That call works fine when the first call is commented out and 'data' is used instead of 'posts'当第一个调用被注释掉并且使用“数据”而不是“帖子”时,该调用工作正常

your destructured response is wrong:你解构的反应是错误的:

replace:代替:

let { posts } = ...

by:经过:

let { data: posts } = ...

Because Axios always returns a "data" attribute, so you just have to rename it as "posts".因为 Axios 总是返回一个“data”属性,所以你只需要把它重命名为“posts”。

Your array concatenation must be like that:您的数组连接必须是这样的:

data.concat(posts);

(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat ) (参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat


The push() method is only to push one item, but not an array of item. push()方法只是推送一个项目,而不是一个项目数组。

(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push ) (参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM