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

时间:2020-02-07 17:39:30

标签: svelte sapper

我在快递中使用svelte / sapper。

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

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

我的问题是如何使用相对URL从route文件夹中的内部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
}

有没有一种方法可以使用相对网址

1 个答案:

答案 0 :(得分:3)

最简单的方法是使用preloadthis.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>

如果由于某种原因无法实现,则可能需要配置环境变量,例如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
}