Fetch with absolute url prefix

痴心易碎 提交于 2020-04-16 05:24:10

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/42470822/fetch-with-absolute-url-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!