Fetch with absolute url prefix

zurfyx picture zurfyx · Feb 26, 2017 · Viewed 9.5k times · Source

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

Answer

zurfyx picture zurfyx · Feb 26, 2017

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!' });
});