【问题标题】:Where should i put Axios baseUrl conf in sveltekit project?我应该把 Axios baseUrl conf 放在 sveltekit 项目的什么地方?
【发布时间】:2023-02-24 02:17:41
【问题描述】:

一切都在标题中,更具体地说,我正在使用 orval rest 客户端生成器。在文档中它说你可以为 axios 配置 baseUrl。但我真的不知道我应该把这种配置放在 svletekit 项目中的什么地方,也许是 index.js?

https://orval.dev/guides/set-base-url#:~:text=Axios.defaults.baseURL%20%3D%20%27%3CBACKEND%20URL%3E%27%3B%20//%20use%20your%20own%20URL%20here%20or%20environment%20variable

【问题讨论】:

    标签: axios sveltekit rest-client


    【解决方案1】:

    Axios 似乎有这样的设置:

    • 如果baseUrlhttps://api.example.com
    • /endpoint/path/的请求将得到https://api.example.com/endpoint/path/

    首先,不要将 Axios 与 SvelteKit 一起使用。 SvelteKit 有一个特殊版本的fetch(),应该改用它。

    SvelteKit (fetch()) 没有像axios.baseURL 这样的设置。

    • 因此您必须使用完整路径调用外部 API。
    • 内部 API 可以通过相关请求调用。

    您可以围绕 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/')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 2012-03-29
      相关资源
      最近更新 更多