reactjs - 动态生成的站点地图 - 站点地图上只有声明的页面
问题描述
我想为每个 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
我得到的只是声明的页面
我试过这样但也不起作用:
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,
});
});
解决方案
您不能从 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中给出的示例
推荐阅读
- python - 如何在 tensorflow2-gpu 中调试内存不足
- android - Flutter Firestore 使用 setDate 批量写入并合并
- python - python中的函数和方法
- ios - App Store Connect:在提交审核后使用“手动发布此版本”自动发布/更新应用程序
- mysql - 在 MySQL 中是否可以选择包含在另一列中引用的部分的字符串?
- php - 为什么 AWS Cloudfront 使用 Signed Urls 时出现 403 错误
- icloud - 如何删除 Apple iCloud 开发数据库中的自定义字段?
- python - 重新排列python pandas中的列
- android - 带有 Android Studio 的 Mac 上的 GitLab 问题:SSL 对等握手失败,GitLab 存储库
- sql - Azure 数据工厂 - SQL 到嵌套 JSON