Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

svelte

sapper

I am using svelte/sapper with express.

I have an api in routes/billing/index.js

It needs to fetch data from customers/[customernumber]/detections.js

My question is how to fetch data from internal apis with in the routes folder using relative URLs

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
}

Is there a way to do this using relative url

like image 976
Narasimhan Avatar asked Mar 03 '23 20:03

Narasimhan


1 Answers

The easiest way is to fetch this data inside preload, using this.fetch, since that will automatically handle relative URLs the same way whether it's running on server or client:

<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>

If that's not possible for whatever reason, you might need to configure an environment variable, e.g. 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
}
like image 189
Rich Harris Avatar answered Apr 09 '23 16:04

Rich Harris