本文介绍了使用绝对网址前缀获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,我为获取或 node-fetch http://localhost(使其成为绝对网址).

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

除了简单地将localhost放在变量中之外,还有什么方法可以避免localhost部分?

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

const baseUrl = 'http://localhost';

fetch(`${baseUrl}/whatever`)

具有绝对URL前缀的超级代理 非常相关

Very related to Superagent with absolute url prefix

推荐答案

TL; DR: 绝对获取可以做到这一点.

详细信息:

您可以在 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!' });
});

这篇关于使用绝对网址前缀获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 12:21