Headers Factory
Opinionated headers factory for easy use with fetch and other AJAX things too I guess.
99% of the time I'm hitting a JSON API in CORS mode, getting or posting some data, and maybe sending up a JWT token.
So I've designed this module to make that use case super easy.
Install
# with npm npm install --save headersfactory # with yarn yarn add headersfactory
Use
headersFactory(jwtToken)(method, data)
// with es6import headersFactory from 'headersfactory'; // with CommonJSconst headersFactory = ; // Example get with no JWT tokenconst githubUrl = 'https://api.github.com/users/tylerbuchea/repos?sort=updated';const githubHeaders = 'get'; ; // Example post and get with JWT tokenconst madeupUrl = 'https://api.example.com/users';const jwtToken = 'IMAJWTTOKEN'; // no need add "Bearer " it is added automatically // No we can use headers() to generate new headers with the JWT token automatically connectedconst headers = ; const headersPost = ; // JSON is automatically strinigified and attached to the body of the request ; // We can use headers() again and the JWT is still automatically attached even though we're performing a different callconst headersGet = ; ;
The actual code
This whole module is super tiny feel free to just copy paste it into your own file locally and modify as opposed to npm install
-ing it.
'use strict'; { return { var header = mode: 'cors' method: method headers: Accept: 'application/json' 'Content-Type': 'application/json' ; if jwtToken headerheadersAuthorization = 'Bearer ' + jwtToken; if data headerbody = JSON; return header; };} moduleexports = headersFactory;