【发布时间】:2023-02-24 02:17:41
【问题描述】:
一切都在标题中,更具体地说,我正在使用 orval rest 客户端生成器。在文档中它说你可以为 axios 配置 baseUrl。但我真的不知道我应该把这种配置放在 svletekit 项目中的什么地方,也许是 index.js?
【问题讨论】:
标签: axios sveltekit rest-client
一切都在标题中,更具体地说,我正在使用 orval rest 客户端生成器。在文档中它说你可以为 axios 配置 baseUrl。但我真的不知道我应该把这种配置放在 svletekit 项目中的什么地方,也许是 index.js?
【问题讨论】:
标签: axios sveltekit rest-client
Axios 似乎有这样的设置:
baseUrl是https://api.example.com
/endpoint/path/的请求将得到https://api.example.com/endpoint/path/
首先,不要将 Axios 与 SvelteKit 一起使用。 SvelteKit 有一个特殊版本的fetch(),应该改用它。
SvelteKit (fetch()) 没有像axios.baseURL 这样的设置。
您可以围绕 SvelteKit 的 fetch() 编写一个自定义包装器,它完成与 axios.baseURL 相同的事情。编写一个将 fetch() 函数作为输入的函数,并输出使用基本 URL 的自定义提取:
const makeFetchWithBaseUrl = (fetchFunction, baseUrl) => {
// Return a function with same the signature as fetch().
return (resource, options) => {
// If resource is a string that doesn't start with 'http' prepend baseUrl.
if (typeof resource === 'string' && /^http:/.test(resource)) {
resource = baseUrl + resource
}
// Call the original fetch
return fetchFunction(resource, options)
}
}
然后你可以像这样使用上面的函数:
// Make custom fetch function:
const exampleComFetch = makeFetchWithBaseUrl(fetch, 'https://example.com/')
// Then use it:
const response = await exampleComFetch('myEndpoint/path/')
【讨论】: