如何使用 sveltekit 提供纯 json 文件?
How to serve plain json files with sveltekit?
我试着在我的端点上做这样的事情
routes/users.json.ts :
import * as api from '$lib/api'
export async function get({ query, locals }) {
const response = await this.fetch('static/data/customers.json')
return {
status: 200,
body: {
data: response
}
}
}
我的静态文件夹位于路由文件夹中。
我收到这个错误:
...
TypeError [ERR_INVALID_URL]: Invalid URL: /static/data/customers.json
at onParseError (internal/url.js:259:9)
at new URL (internal/url.js:335:5)
at new Request (file:///home/nkostic/code/example/node_modules/@sveltejs/kit/dist/install-fetch.js:1239:16)
...
我错过了什么?
重要的是它必须是静态 json 文件。
SvelteKit 的 static
目录输出到已发布文件夹的根目录,因此您无需在路径中包含 static
。请尝试获取 /data/customers.json
。
正如@evolutionxbox 指出的那样,在您的情况下,您需要导入而不是获取。还好vite支持direct imports of .json files.
这样我们就可以简单地导入文件顶部的 .json 并为其分配一个别名,如下所示:
import * as api from '$lib/api'
import yourJSON as api from 'path-to-file/customers.json'
export async function get({ query, locals }) {
return {
status: 200,
body: {
yourJSON
}
}
}
- 将要加载的 json 个文件放入 ./static
- 使用
<script context="module">
里面的加载函数来获取数据。
<script context="module">
export async function load({ fetch }) {
const response = await fetch(`../posts.json`); // stored in static folder
const posts = await response.json();
return {
props: {
posts: posts
}
}
}
</script>
<script>
export let posts;
<script>
详细教程请看这里:https://codesource.io/how-to-fetch-json-in-svelte-example/
我试着在我的端点上做这样的事情 routes/users.json.ts :
import * as api from '$lib/api'
export async function get({ query, locals }) {
const response = await this.fetch('static/data/customers.json')
return {
status: 200,
body: {
data: response
}
}
}
我的静态文件夹位于路由文件夹中。
我收到这个错误:
...
TypeError [ERR_INVALID_URL]: Invalid URL: /static/data/customers.json
at onParseError (internal/url.js:259:9)
at new URL (internal/url.js:335:5)
at new Request (file:///home/nkostic/code/example/node_modules/@sveltejs/kit/dist/install-fetch.js:1239:16)
...
我错过了什么?
重要的是它必须是静态 json 文件。
SvelteKit 的 static
目录输出到已发布文件夹的根目录,因此您无需在路径中包含 static
。请尝试获取 /data/customers.json
。
正如@evolutionxbox 指出的那样,在您的情况下,您需要导入而不是获取。还好vite支持direct imports of .json files.
这样我们就可以简单地导入文件顶部的 .json 并为其分配一个别名,如下所示:
import * as api from '$lib/api'
import yourJSON as api from 'path-to-file/customers.json'
export async function get({ query, locals }) {
return {
status: 200,
body: {
yourJSON
}
}
}
- 将要加载的 json 个文件放入 ./static
- 使用
<script context="module">
里面的加载函数来获取数据。
<script context="module">
export async function load({ fetch }) {
const response = await fetch(`../posts.json`); // stored in static folder
const posts = await response.json();
return {
props: {
posts: posts
}
}
}
</script>
<script>
export let posts;
<script>
详细教程请看这里:https://codesource.io/how-to-fetch-json-in-svelte-example/