更新时间:2021-08-17 08:16:48
因此,一开始可能会造成混淆.要使此工作正常进行,您需要在本地代理您的提取.这是您可以执行的操作:
So this can be a bit confusing in the beginning. To get this working you need to proxy your fetches locally. Here's how you can do that:
在/posts/index.json.js
中:
let contents;
export function get(req, res) {
const posts = fetch('do stuff here to fetch')
contents = JSON.stringify(posts);
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(contents);
}
在您实际的路线组件/posts/index.svelte
中:
And in your actual route component /posts/index.svelte
:
<script context="module">
export async function preload({ params, query }) {
return this.fetch(`index.json`).then(r => r.json()).then(posts => {
return { posts };
});
}
</script>
<script>
export let posts;
</script>
官方 Svelte网站使用此方法获取帖子(从本地文件而不是使用访存).您可能会从中得到一些启发.
The official Svelte website uses this approach to get posts (from a local file rather than using fetch though). You can probably get some inspiration from that.
值得一提的是,preload()
函数既被提供给服务器,也被提供给前端,因此您不应在其中放置API密钥.
It is worth mentioning that the preload()
function is shipped both to the server and the front-end so you should not put API keys there.