我正在使用sapper启动模板https://github.com/sveltejs/sapper-template,并且对如何从外部API(在本例中为WordPress)获取数据的方法感到困惑。
我修改了/blog/_posts.js,其中包含const = posts = [...all the json..]
-首先我尝试将其替换为const = posts = fetch('http://localhost:9000/wp-json/wp/v2/posts');
,这导致未定义错误提取-因此,我包含了node-fetch-现在返回服务器js posts.map is not a function
我一直在阅读以尝试找到答案,并尝试过类似的事情:
let posts;
export async function preload(page, session) {
posts = await this.fetch('http://localhost:9000/wp-json/wp/v2/posts');
return { posts }; }
export default posts;
_posts.js中的会导致: const contents = JSON.stringify(posts $ 1.map(post => { TypeError:无法读取未定义的属性“地图”
不幸的是,我找不到任何文档或示例来实现此目的-因此,在我尝试学习精简工具时,请多多指教。
答案 0 :(得分:0)
调用this.fetch
(或fetch
)的结果是一个Response
对象,不是数据。您需要执行以下操作:
export async function preload(page, session) {
const r = await this.fetch('http://localhost:9000/wp-json/wp/v2/posts');
return {
posts: await r.json()
};
}
不要在函数主体之外定义posts
,也不要在export default
中定义<script>
。