2017-02-26 8 views
0

ほとんどの場合、私はfetchまたはnode-fetchの接頭辞にはhttp://localhost(これは絶対URLにする)の前に付いています。絶対URL接頭辞付きのフェッチ

import fetch from 'node-fetch'; 

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

localhost部分を避けて任意の方法は、単に変数にlocalhostを配置する以外、ありますか?

const baseUrl = 'http://localhost'; 

fetch(`${baseUrl}/whatever`) 

は非常にSuperagent with absolute url prefix

答えて

0

TLに関連し; DR:fetch-absoluteは、まさにその作業を行います。詳細

あなたはfetchの上に1つの抽象化レイヤを作成することができます。

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

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!' }); 
}); 
関連する問題