3

我尝试在我的端点 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 文件。

4

2 回答 2

6

正如@evolutionxbox 指出的那样,在您的情况下,您需要导入而不是获取。幸运的是 vite 支持直接导入 .json 文件

这使我们可以简单地在文件顶部导入 .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
    }
  }

}
于 2021-06-12T01:37:39.493 回答
1

SvelteKit 的static目录输出到您发布的文件夹的根目录,因此您不需要包含static在您的路径中。尝试/data/customers.json取而代之。

于 2021-06-12T01:28:37.837 回答