首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用sitemap包在next js中生成动态站点地图?

如何用sitemap包在next js中生成动态站点地图?
EN

Stack Overflow用户
提问于 2021-08-22 20:44:21
回答 1查看 67关注 0票数 0

我正在为我的web应用程序使用next js和back4app。我偶然发现sitemap库想要写一个sitemap,但是我根本不能创建一个动态的站点地图。我不能运行任何api调用或云代码,我有一个特定的函数,它将返回所有的路由,以便我可以管道它们。下面是我的示例代码:

代码语言:javascript
复制
import { SitemapStream, streamToPromise } from "sitemap";
const {Readable} = require("stream");
import cacheData from 'memory-cache';
import { initializeParse } from '@parse/react-ssr';



initializeParse( 
    'https://parseapi.back4app.com',
    '********************',
    '*********************'
  );

const sitemap = async (req,res) => {

    try{
        const links = [
            { url: "/blogggy", changefreq: "daily", priority: 0.3 },
        ];
        const userParams = {
            authKey: "***********************"
        }


         Parse.Cloud.run("getAllRoutes",userParams).then(response =>{
             response.map((handle) => {
                 links.push({
                   url: `/${handle}`,
                   changefreq: "daily",
                   priority: 0.9,
                 });
               })
         }).catch(e =>{
             res.send(JSON.stringify(e));
         })
        

        const pages = ["/explore"];
        pages.map((url) => {
          links.push({
            url,
            changefreq: "daily",
            priority: 0.9,
          });
        });
        
        const stream = new SitemapStream({hostname: `https://${req.headers.host}`}) ; 
        
        res.writeHead(200,{
            "Content-Type": "application/xml",
        });
        
        const xmlString = await streamToPromise(
            Readable.from(links).pipe(stream)
        ).then((data) => data.toString());
        
        res.end(xmlString);
    }
    catch(e){
        console.log(e);
        res.send(JSON.stringify(e));
    }
};


export default sitemap

我也尝试过getServerSideProps,但它不起作用。我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-23 16:25:52

同样,我不确定这是否是您的代码的唯一问题,但请尝试将云代码函数调用重写为如下所示:

代码语言:javascript
复制
let response;
try {
  response = await Parse.Cloud.run("getAllRoutes",userParams);
}
catch (e) {
  res.send(JSON.stringify(e));
  return;
}
response.map((handle) => {
  links.push({
    url: `/${handle}`,
    changefreq: "daily",
    priority: 0.9,
  });
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68885006

复制
相关文章

相似问题

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