它实际上是在生产环境中工作的,只是在开发环境中不起作用
npm run dev
.我看到一个问题,你必须使用
load({ fetch })
当然可以,但这并不理想。
预加载:
<script context="module">
import Stats from '$api/stats';
export async function load({}) {
const tags = (await Stats.getTags()).tags.sort((a, b) => {
return a.word.localeCompare(b.word);
});
return {
props: {
tags
}
};
}
</script>
统计数据。js
import api from './create-api';
class Stats {
static async getStats() {
return await api('/stats');
}
static async getTags() {
return await api('/tags');
}
}
export default Stats;
创建api。js
import { browser } from '$app/env';
async function api(path, body = {}, opts = {}) {
path = import.meta.env.VITE_API_ENDPOINT + path;
body = JSON.stringify(body);
const method = opts.method || 'GET';
const auth = browser ? 'Bearer ' + localStorage.getItem('token') : '';
const headers = {};
if (auth) {
headers.Authorization = auth;
}
const res = await fetch(path, {
method: opts.method || 'GET',
body: method == 'GET' ? null : body,
headers
});
if (res.ok) {
return await (opts.raw ? res.text() : res.json());
}
throw res;
}
export default api;
有没有办法从我的网站上导入更苗条的fetch版本
create-api.js
或者我必须把它从使用它的Stats实例一直传递下去吗?