首页 > 解决方案 > 动态生成的站点地图 - 站点地图上只有声明的页面

问题描述

我想为每个 slug 生成动态 url,但是有一个数组只包含我声明的页面:const pages = ["/", "/about", "/portfolio", "/blog"]; http://localhost:3000/api/my-sitemap。我已经从https://www.npmjs.com/package/sitemap安装了 npm 站点地图

我在 ../../lib/data.js 中的查询

export const getBlogSlugs = async () => {
  const endpoint =
    "https://api-eu-central-gsagasgasxasasxsaxasxassaster";

  const graphQLClient = new GraphQLClient(endpoint);

  const query = gql`
    {
      posts {
        slug
      }
    }
  `;
  return await graphQLClient.request(query);
};

页面/api/my-sitemap.js

import { getBlogSlugs } from "../../lib/data";
const { SitemapStream, streamToPromise } = require("sitemap");
const { Readable } = require("stream");

export const getStaticProps = async () => {
  const { posts } = await getBlogSlugs();
  return {
    props: {
      posts,
    },
  };
};

export default async (req, res, posts) => {
  try {
    const links = [];
    posts?.map((slug) => {
      links.push({
        url: `/blog/${slug}`,
        changefreq: "daily",
        priority: 0.9,
      });
    });

    // Add other pages
    const pages = ["/", "/about", "/portfolio", "/blog"];
    pages.map((url) => {
      links.push({
        url,
        changefreq: "daily",
        priority: 0.9,
      });
    });

    // Create a stream to write to
    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));
  }
};

我在 pudblic 文件夹中添加了我的 robots.txt:

User-agent: *
Allow: /

Sitemap: http://localhost:3000/api/my-sitemap

我得到的只是声明的页面

本地主机:3000/api/my-sitemap

我试过这样但也不起作用:

export const getStaticProps = async () => {
  const data = await getBlogSlugs();
  return {
    props: {
      posts: data.posts,
    },
  };
};

export default async (req, res, posts) => {
  try {
    const links = [];
    posts?.map((post) => {
      links.push({
        url: `/blog/${post.slug}`,
        changefreq: "daily",
        priority: 0.9,
      });
    });

标签: reactjsnext.jsseo

解决方案


您不能从 API 路由中使用 getStaticProps。 https://github.com/vercel/next.js/discussions/16068#discussioncomment-703870

您可以直接在 API 函数中获取数据。

编辑:在我的应用程序中,我使用下面的 API 路由代码从外部服务器获取数据

import fetch from "isomorphic-unfetch";

export default async (req, res) => {
  try {
    const result = await fetch("YOUR_URL");
    const posts = await result.json();
//use posts
    });
  } catch (e) {}
};

对于 GraphQl,您可以查看 vercel 站点 https://github.com/vercel/next.js/tree/canary/examples/api-routes-graphql中给出的示例


推荐阅读