使用绝对 url 前缀获取

zur*_*fyx 5 absolute-path fetch node.js node-fetch

大多数时候,我在fetchnode-fetch前面加上一个前缀http://localhost(使其成为绝对 URL)。

import fetch from 'node-fetch';

fetch('http://localhost/whatever')
Run Code Online (Sandbox Code Playgroud)

localhost除了简单地放入localhost变量之外,是否有任何方法可以避免该部分?

const baseUrl = 'http://localhost';

fetch(`${baseUrl}/whatever`)
Run Code Online (Sandbox Code Playgroud)

与具有绝对 url 前缀的 Superagent非常相关

zur*_*fyx 4

TL;DR: fetch-absolute正是这样做的。

详细的:

您可以在fetch之上创建一个抽象层。

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

或者您可以简单地使用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!' });
});
Run Code Online (Sandbox Code Playgroud)