Svelte/Sapper 如何在不给出绝对 URL 的情况下从内部 api 获取数据

Svelte/Sapper How to fetch data from internal api without giving absolute URL

我正在使用 svelte/sapper 快递。

我在 routes/billing/index.js

中有一个 api

需要从customers/[customernumber]/detections.js

获取数据

我的问题是如何使用相对 URL

从路由文件夹中的内部 api 获取数据
async function getDataFromGateway(customerNumber) {
  if (typeof fetch !== 'function') {
    global.fetch = require('node-fetch')
  }
  const data = await fetch(`http://localhost:19052/customers/${customerNumber}/detections`)
    .then(res => res.json())
    .catch(error => {
      console.log(error)
      return error
    }
    )
  return data
}

有没有办法使用相对 url

最简单的方法是使用 this.fetchpreload 中获取此数据,因为无论它是 运行 服务器还是客户端,它都会以相同的方式自动处理相对 URL:

<script context="module">
  export async function preload(page, session) {
    const r = await this.fetch(`customers/${getCustomerNumber(session)}/detections`);
    const data = await r.json();

    return {
      foo: data.foo
    };
  }
</script>

如果出于某种原因无法做到这一点,您可能需要配置一个环境变量,例如BASE_URL:

async function getDataFromGateway(customerNumber) {
  if (typeof fetch !== 'function') {
    global.fetch = require('node-fetch')
  }
  const data = await fetch(`${process.env.BASE_URL}/customers/${customerNumber}/detections`)
    .then(res => res.json())
    .catch(error => {
      console.log(error)
      return error
    }
    )
  return data
}