amp-next-page无限滚动异常:加载首篇后无法加载后续内容求助
问题描述
使用amp-next-page实现新闻无限滚动时出现异常:滚动到主文章底部能加载第一篇文章,但继续滚动该文章时,无法加载next属性指定的下一组JSON数据。
页面代码
<amp-next-page src={http://localhost:3000/api/getInfinitiveTape?page=${page}&locale=${router.locale}}></amp-next-page>
API处理代码(Next.js)
export default async function handler(req: NextApiRequest, res: NextApiResponse<Data>) { const { locale = '', page = 1 } = req.query; const data = await apiGetOnePost({ page: parseInt(page as string), limit: 1, }, locale as string); const item = transformArticle(data, moduleId); const baseUrl = req.headers.host; const pageUrl = req.url; const baseProtocol = req.headers['x-forwarded-proto']; if (!baseUrl) { res.status(500).json({ message: 'baseUrl is not defined', }); return; } const requestUrl = 'http://localhost:3000'; const nextUrl = new URL(requestUrl); nextUrl.pathname = '/api/getInfinitiveTape'; nextUrl.searchParams.set('page', String(Number(page) + 1)); nextUrl.searchParams.set('locale', 'uk'); const url = new URL(requestUrl); url.pathname = `cosmetology/${item.seo?.[`slug_${locale}`] as string}/amp`; res.status(200).json({ pages: [{ ...item, image: `${item.s3}${item.image}`, title: item.title as string, url: url.toString(), }], next: nextUrl.toString(), }); }
API返回的JSON结构
{ "pages": [ { "id": 5037, "title": "test", "sub_title": "subtest", "publication_date": "2023-03-08", "image": "/images/News/test.jpg", "url": "http://localhost:3000/mySite/siteSlug/amp" } ], "next": "http://localhost:3000/api/getInfinitiveTape?page=2&locale=uk" }
期望效果
滚动到无限流中的最后一篇文章时,自动加载下一组数据的JSON。
排查与解决建议
1. 验证next URL的有效性
直接在浏览器中访问next字段返回的URL(如http://localhost:3000/api/getInfinitiveTape?page=2&locale=uk),确认:
- 能正常返回符合格式的JSON数据
next字段正确指向page=3的地址- 若page=2的API返回异常(无数据、格式错误),
amp-next-page会停止加载后续内容
2. 检查AMP页面合规性
确保pages[0].url指向的文章页面符合AMP规范:
- 包含完整的AMP boilerplate代码
- 无违反AMP规则的自定义脚本或样式
- 用AMP官方验证工具检查页面合法性,非法页面会导致
amp-next-page无法触发后续加载
3. 修正API返回数据的细节
- 将
image字段改为完整绝对URL(当前是相对路径/images/News/test.jpg,建议改为http://localhost:3000/images/News/test.jpg) - 确认
title字段不为空,所有必填字段格式符合AMP要求
4. 排查跨域问题
若主页面与API不在同一域名,需在API响应中添加CORS头:
res.setHeader('Access-Control-Allow-Origin', '*'); // 或指定具体域名 res.setHeader('Access-Control-Allow-Methods', 'GET');
5. 查看AMP调试日志
在浏览器开发者工具的Console面板中,查看AMP相关错误提示,amp-next-page加载失败时通常会输出明确的错误信息,根据提示定位问题。
内容的提问来源于stack exchange,提问作者Рома Зайчук
相关产品推荐
相关产品推荐

