fetch-http-client (2024)

fetch-http-client (1) fetch-http-client (2) fetch-http-client (3) fetch-http-client (4)

A http client wrapper for Fetch API with middleware support.

Fetch API is a elegant way to access HTTP resources. I used it in my React/ReactNative project as the default network layer. But it still has some inconvenience to use. For example, every request should carry the access token in HTTP request headers, ervery request error should be logged to console etc.

If Fetch API support middleware, everything can be elegantly fixed. Both fetch-plus and http-client provided the middleware support, but if you need some asynchronous pre-request opreation, they could not suppport elegantly.

So this project is another choice to use Fetch API with middleware support, it's quite simple and powerful.

npminstallfetch-http-client--save

Import

importFetchHttpClient,{json}from'fetch-http-client';

Quick start

//Createanewclientobject.

constclient=newFetchHttpClient('http://api.example.com/endpoint');

//Addaccesstoken

client.addMiddleware(request=>{

request.options.headers['X-Access-Token']='secret';

});

//Addjsonsupport

client.addMiddleware(json());

//AddLogging

client.addMiddleware(request=>response=>{

console.log(request,response);

});

//Firerequest.

client.get('test').then(response=>console.log(response.jsonData));

//Pathvariablessupport.

client.get('users/{id}',{uriParams:{id:1}}).then(response=>console.log(response.jsonData));

Asynchronous pre-request middleware

if your access token is stored in a asynchronous storage, it should be fetch before every request, you can use such kind of middleware:

//Addaccesstokenasynchronously

client.addMiddleware(request=>{

returnAsynchronousStorage.fetch('accessToken').then(token=>{

request.options.headers['X-Access-Token']=token;

returnrequest;

});

});

That means your middleware could return a Promise object and the real request opreate will be issued after the asynchronous method finished.

NEVER forget returning the request object after you handled the result!

FetchHttpClient

newFetchHttpClient(baseUrl:string);

fetch

fetch method can been used the same as Fetch API.

instance.fetch(uri:string[, options: object])

request

Convenience way to issue a request with specific verb.

instance.request(uri:string, method:string[, options: object])

get

Convenience way to issue a GET request.

instance.get(uri:string[, options: object])

post

Convenience way to issue a POST request.

instance.post(uri:string[, options: object])

put

Convenience way to issue a PUT request.

instance.put(uri:string[, options: object])

delete

Convenience way to issue a DELETE request.

instance.delete(uri:string[, options: object])

patch

Convenience way to issue a PATCH request.

instance.patch(uri:string[, options: object])

Build-in middlewares

query

This middleware could add the ability to append object value to query string:

//Addquerymiddleware

client.addMiddleware(query());

//Request

client.get('test',{

query:{

foo:'FOO',

bar:'BAR',

},

});

It will request to http://api.example.com/endpoint/test?foo=FOO&bar=BAR.

form

Like query, this could be used to handle post form values.

//Addformmiddleware

client.addMiddleware(form());

//Request

client.post('test',{

form:{

foo:'FOO',

bar:'BAR',

},

});

header

A convenience middleware to add headers to request.

//Addheadermiddleware

client.addMiddleware(header({

'X-Request-By':'FetchHttpClient',

}));

userAgent

A convenience middleware to set User-Agent to headers.

//Addheadermiddleware

client.addMiddleware(userAgent({

'Client':'1.1',

}));

json

Convert object to request and parse from response.

//Addjsonmiddleware

client.addMiddleware(json());

//Request

client.post('add',{

json:{

foo:'FOO',

},

}).then(response=>{

console.log(response.jsonData);

});

timeout

Set timeout options to fetch.

//Addtimeoutmiddleware

client.addMiddleware(timeout(1000));

credentials

Set credentials options to fetch. If you want to automatically send cookies for the current domain, use this middleware and config it as same-origin.

//Addcredentialsmiddleware

client.addMiddleware(credentials('same-origin'));

If you have any questions, use Issues.

Sina Weibo: @starlight36

MIT Licence.

fetch-http-client (2024)
Top Articles
What does "buying the dip" mean?
The 5 Key Steps to Starting a 6-Figure Coaching Business in 2019
Hometown Pizza Sheridan Menu
Fiskars X27 Kloofbijl - 92 cm | bol
Skylar Vox Bra Size
Triumph Speed Twin 2025 e Speed Twin RS, nelle concessionarie da gennaio 2025 - News - Moto.it
Konkurrenz für Kioske: 7-Eleven will Minisupermärkte in Deutschland etablieren
Miles City Montana Craigslist
Bloxburg Image Ids
Okatee River Farms
Displays settings on Mac
Mephisto Summoners War
UEQ - User Experience Questionnaire: UX Testing schnell und einfach
Burn Ban Map Oklahoma
Enterprise Car Sales Jacksonville Used Cars
Daily Voice Tarrytown
Idaho Harvest Statistics
The best TV and film to watch this week - A Very Royal Scandal to Tulsa King
Tamilyogi Proxy
Schedule 360 Albertsons
Costco Great Oaks Gas Price
Best Mechanics Near You - Brake Masters Auto Repair Shops
Great Clips Grandview Station Marion Reviews
Prot Pally Wrath Pre Patch
Parkeren Emmen | Reserveren vanaf €9,25 per dag | Q-Park
Malluvilla In Malayalam Movies Download
manhattan cars & trucks - by owner - craigslist
Darktide Terrifying Barrage
Courtney Roberson Rob Dyrdek
R/Sandiego
3473372961
Angela Muto Ronnie's Mom
Sun-Tattler from Hollywood, Florida
Sun Haven Pufferfish
Roto-Rooter Plumbing and Drain Service hiring General Manager in Cincinnati Metropolitan Area | LinkedIn
B.C. lightkeepers' jobs in jeopardy as coast guard plans to automate 2 stations
How Many Dogs Can You Have in Idaho | GetJerry.com
Jack In The Box Menu 2022
Barstool Sports Gif
Firestone Batteries Prices
Callie Gullickson Eye Patches
Ucsc Sip 2023 College Confidential
Ehc Workspace Login
Backpage New York | massage in New York, New York
Neil Young - Sugar Mountain (2008) - MusicMeter.nl
Displacer Cub – 5th Edition SRD
Bedbathandbeyond Flemington Nj
Ronnie Mcnu*t Uncensored
Morgan State University Receives $20.9 Million NIH/NIMHD Grant to Expand Groundbreaking Research on Urban Health Disparities
Who We Are at Curt Landry Ministries
Texas Lottery Daily 4 Winning Numbers
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 5666

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.