5

Most of the times I prefix fetch or node-fetch with an http://localhost (to make it an absolute url).

import fetch from 'node-fetch';

fetch('http://localhost/whatever')

Is there any way of avoiding the localhost part, other than simply placing localhost in a variable?

const baseUrl = 'http://localhost';

fetch(`${baseUrl}/whatever`)

Very related to Superagent with absolute url prefix

Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145

2 Answers2

4

TL;DR: fetch-absolute does exactly that.

Detailed:

You can create one abstraction layer on top of fetch.

function fetchAbsolute(fetch) {
  return baseUrl => (url, ...otherParams) => url.startsWith('/') ? fetch(baseUrl + url, ...otherParams) : fetch(url, ...otherParams)
}

Or you can simply use fetch-absolute.

const fetch = require('node-fetch');
const fetchAbsolute = require('fetch-absolute');

const fetchApi = fetchAbsolute(fetch)('http://localhost:3030');

it('should should display "It works!"', async () => {
  const response = await fetchApi('/');
  const json = await response.json();
  expect(json).to.eql({ msg: 'It works!' });
});
zurfyx
  • 31,043
  • 20
  • 111
  • 145
3

You can override the fetch function:

import origFetch from 'node-fetch';

const fetch = (url, ...params) => {
  if (url.startsWith('/')) return origFetch('http://localhost' + url, ...params)
  else return origFetch(url, ...params);
}

The other answer creates a function that returns a function that returns a function--that's not necessary; you just need to return a function.

function fetchAbsolute(fetch, base_url) {
  return (url, ...params) => {
    if (url.startsWith('/')) return fetch(base_url + url, ...params)
    else return fetch(url, ...params);
  }
}

const fetch = fetchAbsolute(origFetch, 'http://localhost');
FelipeC
  • 9,123
  • 4
  • 44
  • 38