Svelte / Sapper Как получить данные из внутреннего API без указания абсолютного URL - PullRequest
1 голос
/ 07 февраля 2020

Я использую svelte / sapper с express.

У меня есть API в routes/billing/index.js

Необходимо получить данные из customers/[customernumber]/detections.js

У меня вопрос, как получить данные из внутреннего API в папке маршрутов использование относительных URL

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

1 Ответ

1 голос
/ 07 февраля 2020

Самый простой способ - извлечь эти данные из 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>

Если это по какой-либо причине это невозможно, вам может потребоваться настроить переменную среды, например 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
}
...