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

Nar*_*han 4 svelte sapper

我正在使用带有快递的苗条/工兵。

我有一个 api routes/billing/index.js

它需要从中获取数据 customers/[customernumber]/detections.js

我的问题是如何使用相对 URL 从路由文件夹中的内部 apis 中获取数据

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
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用相对网址来做到这一点

Ric*_*ris 7

最简单的方法是取里面这个数据preload,使用this.fetch,因为它会自动处理相对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>
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因无法做到这一点,您可能需要配置一个环境变量,例如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
}
Run Code Online (Sandbox Code Playgroud)