Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🐕 Modern fetch-based alternative to axios/superagent/request. Great for React Native.

License

NotificationsYou must be signed in to change notification settings

ladjs/frisbee

Repository files navigation

Slack Statusnpm versionnpm downloadsbuild statuscode coveragecode stylestyled with prettiermade with lasslicense

❤️ Love this project? Support@niftylettuce'sFOSS onPatreon orPayPal 🦄

Modernfetch-based alternative toaxios/superagent/request. Great forReact Native.

New in v2.0.4++:baseURI is now optional and you can passraw: true as a global or request-based option to get the rawfetch() response (e.g. if you want to useres.arrayBuffer() orany other method manually).

Table of Contents

Install

Node (Koa, Express, React Native, ...)

  1. Install the required package:

    npm install --save frisbee
  2. Seeusage example and API below

Browser

VanillaJS

  1. Load the package via<script> tag (note you will need to polyfill withrequired features):
<scriptcrossorigin="anonymous"src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=es6,Array.from,Object.getOwnPropertyDescriptors,Object.getOwnPropertySymbols,Promise,Promise.race,Promise.reject,Promise.resolve,Reflect,Symbol.for,Symbol.iterator,Symbol.prototype,Symbol.species,Symbol.toPrimitive,Symbol.toStringTag,Uint8Array"></script><scriptsrc="https://unpkg.com/frisbee"></script><scripttype="text/javascript">(function(){// create a new instance of Frisbeevarapi=newFrisbee({baseURI:'https://api.startup.com',// optionalheaders:{'Accept':'application/json','Content-Type':'application/json'}});// this is a simple example using `.then` and `.catch`api.get('/hello-world').then(console.log).catch(console.error);//// see the Usage section below in Frisbee's README for more information// https://github.com/niftylettuce/frisbee//})();</script>
  1. Seeusage example and API below for a more complete example.

Bundler

  1. Install the required package:

    npm install frisbee
  2. Ensure that your environment is polyfilled withrequired features (e.g. use@babel/polyfill globally or a service likepolyfill.io)

  3. Seeusage example and API below

Usage

Example

constFrisbee=require('frisbee');// create a new instance of Frisbeeconstapi=newFrisbee({baseURI:'https://api.startup.com',// optionalheaders:{'Accept':'application/json','Content-Type':'application/json'}});// this is a simple example using `.then` and `.catch`api.get('/hello-world').then(console.log).catch(console.error);// this is a more complex example using async/await and basic auth(async()=>{// log in to our API with a user/passtry{// make the requestletres=awaitapi.post('/v1/login');// handle HTTP or API errorsif(res.err)throwres.err;// set basic auth headers for all// future API requests we makeapi.auth(res.body.api_token);// now let's post a message to our APIres=awaitapi.post('/v1/messages',{body:'Hello'});// handle HTTP or API errorsif(res.err)throwres.err;// now let's get a list of messages filtered by page and limitres=awaitapi.get('/v1/messages',{body:{limit:10,page:2}});// handle HTTP or API errorsif(res.err)throwres.err;// now let's logoutres=api.post('/v1/logout');// handle HTTP or API errorsif(res.err)throwres.err;// unset auth now since we logged outapi.auth();// for more information on `fetch` headers and// how to send and expect various types of data:// <https://github.com/github/fetch>}catch(err){console.error(err);}})();

API

constFrisbee=require('frisbee');

Frisbee is a function that optionally accepts an argumentoptions, which is an object full of options for constructing your API instance.

  • Frisbee - accepts anoptions object, with the following accepted options:

    • baseURI (String) - the default URI to use as a prefix for all HTTP requests (optional as of v2.0.4+)

      • If your API server is running onhttp://localhost:8080, then use that as the value for this option

      • If you useReact Native, then you most likely want to setbaseURI as follows (e.g. making use of__DEV__ global variable):

        constapi=newFrisbee({baseURI:__DEV__    ?process.env.API_BASE_URI||'http://localhost:8080'    :'https://api.startup.com'});
      • You could also setAPI_BASE_URI as an environment variable, and then set the value of this option toprocess.env.API_BASE_URI (e.g.API_BASE_URI=http://localhost:8080 node app)

      • UsingReact Native? You might want to read this article aboutautomatic IP configuration.

    • headers (Object) - an object containing default headers to send with every request

      • Tip: You'll most likely want to set the"Accept" header to"application/json" and the"Content-Type" header to"application/json"
    • body (Object) - an object containing default body payload to send with every request. Either the default body set in options will be used or it will be overridden with a request provided body. Body will not merge nor deep merge.

    • params (Object) - an object containing default querystring parameters to send with every request (API method specificparams options will override or extend properties defined here, but will not deep merge)

    • logRequest (Function) - a function that accepts two argumentspath (String) andopts (Object) and will be called with before a fetch request is made with (e.g.fetch(path, opts) – seeLogging and Debugging below for example usage) - this defaults tofalse so no log request function is called out of the box

    • logResponse (Function) - a function that accepts three argumentspath (String),opts (Object), andresponse (Object) and has the same parameters aslogRequest, with the exception of the thirdresponse, which is the raw response object returned from fetch (seeLogging and Debugging below for example usage) - this defaults tofalse so no log response function is called out of the box

    • auth - will call theauth() function below and set it as a default

    • parse - options passed toqs.parse method (seeqs for all available options)

      • ignoreQueryPrefix (Boolean) - defaults totrue, and parses querystrings from URL's properly
    • stringify - options passed toqs.stringify method (seeqs for all available options)

      • addQueryPrefix (Boolean) - defaults totrue, and affixes the path with required? parameter if a querystring is to be passed

      • format (String) - defaults toRFC1738

      • arrayFormat (String) - defaults to'indices'

    • preventBodyOnMethods (Array) - defaults to[ 'GET', 'HEAD', 'DELETE', 'CONNECT' ], and is an Array of HTTP method names that we will convert abody option to be querystringified URL parameters (e.g.api.get('/v1/users', { search: 'foo' }) will result inGET /v1/users?search=foo). According toRFC 7231, the default methods defined here have no defined semantics for having a payload body, and having one may cause some implementations to reject the request (which is why we set this as a default). If you wish to disable this, you may passpreventBodyOnMethods: false or your own custom ArraypreventBodyOnMethods: [ ... ]

    • interceptableMethods (Array) - defaults to all API methods supported below (defaults toGET,HEAD,POST,PUT,DELETE,OPTIONS,PATCH)

    • raw (Boolean) - return a raw fetch response (new as of v2.0.4+)

    • abortToken (Symbol) - some Symbol that you can use to abort one or more frisbee requests

    • signal (Object) - anAbortController Signal used to cancel a fetch request

    • mode (String) - passed to fetch, defaults to "same-origin" (seeFetch's documentation for more info)

    • cache (String) - passed to fetch, defaults to "default" (seeFetch's documentation for more info)

    • credentials (String) - passed to fetch, defaults to "same-origin" (seeFetch's documentation for more info)

    • redirect (String) - passed to fetch, defaults to "follow" (seeFetch's documentation for more info)

    • referrer (String) - passed to fetch, defaults to "client" (seeFetch's documentation for more info)

Upon being invoked,Frisbee returns an object with the following chainable methods:

  • api.auth(creds) - helper function that sets BasicAuth headers, and it acceptsuser andpass arguments

    • You can passcreds user and pass as an array, arguments, or string:([user, pass]),(user, pass), or("user:pass"), so you shouldn't have any problems!
    • If you don't pass bothuser andpass arguments, then it removes any previously set BasicAuth headers from priorauth() calls
    • If you pass only auser, then it will setpass to an empty string'')
    • If you pass: then it will assume you are trying to set BasicAuth headers using your ownuser:pass string
    • If you pass more than two keys, then it will throw an error (since BasicAuth only consists ofuser andpass anyways)
  • api.setOptions(opts) - helper function to update instance options (note this does not callapi.auth internally again even ifopts.auth is passed)

  • api.jwt(token) - helper function that sets a JWT Bearer header. It accepts thejwt_token as a single string argument. If you simply invoke the functionnull as the argument for your token, it will remove JWT headers.

  • api.abort(token) - aborts all current/queued requests that were created usingtoken

  • api.abortAll() - aborts all current/queued - i.e.await-ing in an interceptor - requests

  • All exposed HTTP methods return a Promise, and they require apath string, and accept an optionaloptions object:

    • Accepted method arguments:

      • pathrequired - the path for the HTTP request (e.g./v1/login, will be prefixed with the value ofbaseURI if set)

      • optionsoptional - an object containing options, such as header values, a request body, form data, or a querystring to send along with the request. These options by default are inherited from global options passed tonew Frisbee({ options }). For theGET method (and theDELETE method as of version1.3.0),body data will be encoded in the query string. **Thisoptions object is passed to the native Fetch API method, which means you can use native Fetch API method options as well fromFetch's documentation

        To make only a certain request be raw and not parsed by Frisbee:

        constres=awaitapi.get('/v1/messages',{raw:false});

        Here are a few examples (you can override/merge your set default headers as well per request):

        • To turn off caching, passcache: 'reload' to native fetch options:

          constres=awaitapi.get('/v1/messages',{cache:'reload'});
        • To set a custom header value ofX-Reply-To on aPOST request:

          constres=awaitapi.post('/messages',{headers:{'X-Reply-To':'7s9inuna748y4l1azchi'}});
      • rawoptional - will override a globalraw option if set, and if it istrue it will return a rawfetch response (new as of v2.0.4+)

    • List of available HTTP methods:

      • api.get(path, options) - GET
      • api.head(path, options) - HEAD (does not currently work - see tests)
      • api.post(path, options) - POST
      • api.put(path, options) - PUT
      • api.del(path, options) - DELETE
      • api.delete(path, options) - DELETE
      • api.options(path, options) - OPTIONS (does not currently work - see tests)
      • api.patch(path, options) - PATCH
    • Note that you can chain theauth method and a HTTP method together:

      constres=awaitapi.auth('foo:bar').get('/');
  • interceptor - object that can be used to manipulate request and response interceptors. It has the following methods:

    • api.interceptor.register(interceptor):Accepts an interceptor object that can have one or more of the following functions

      {request:function(path,options){// Read/Modify the path or options// ...return[path,options];},requestError:function(err){// Handle an error occured in the request method// ...returnPromise.reject(err);},response:function(response){// Read/Modify the response// ...returnresponse;},responseError:function(err){// Handle error occured in api/response methodsreturnPromise.reject(err);}

      theregister method returns anunregister() function so that you can unregister the added interceptor.

    • api.interceptor.unregister(interceptor):Accepts the interceptor reference that you want to delete.

    • api.interceptor.clear():Removes all the added interceptors.

    • Note that when interceptors are added in the order ONE->TWO->THREE:

      • Therequest/requestError functions will run in the same orderONE->TWO->THREE.
      • Theresponse/responseError functions will run in reversed orderTHREE->TWO->ONE.

Logging and Debugging

Wehighly recommend touse CabinJS as your Node.js and JavaScript logging utility (seeAutomatic Request Logging for complete examples).

Logging Requests and Responses

You can log both requests and/or responses made to fetch internally in Frisbee. Simply pass alogRequest and/orlogResponse function.

logRequest accepts two argumentspath (String) andopts (Object) and these two arguments are what we callfetch with internally (e.g.fetch(path, opts)):

constcabin=require('cabin');constfrisbee=require('frisbee');constpino=require('pino')({customLevels:{log:30},hooks:{// <https://github.com/pinojs/pino/blob/master/docs/api.md#logmethod>logMethod(inputArgs,method){returnmethod.call(this,{// <https://github.com/pinojs/pino/issues/854>// message: inputArgs[0],msg:inputArgs[0],meta:inputArgs[1]});}}});constlogger=newCabin({// (optional: your free API key from https://cabinjs.com)// key: 'YOUR-CABIN-API-KEY',axe:{logger:pino}});constapi=newFrisbee({logRequest:(path,opts)=>{logger.info('fetch request',{ path, opts});}});

logResponse accepts three arguments, the first two are the same aslogRequest (e.g.path andopts), but the third argument isresponse (Object) and is the raw response object returned from fetch (e.g.const response = await fetch(path, opts)):

constcabin=require('cabin');constfrisbee=require('frisbee');constpino=require('pino')({customLevels:{log:30}});constlogger=newCabin({// (optional: your free API key from https://cabinjs.com)// key: 'YOUR-CABIN-API-KEY',axe:{logger:pino}});constapi=newFrisbee({logResponse:(path,opts,res)=>{logger.info('fetch response',{ path, opts, res});}});

Debug Statements

You can run your application withDEBUG=frisbee node app.js to output debug logging statements with Frisbee.

Common Issues

Required Features

This list is sourced from ESLint output and polyfilled settings througheslint-plugin-compat.

  • Array.from() is not supported in IE 11
  • Object.getOwnPropertyDescriptors() is not supported in IE 11
  • Object.getOwnPropertySymbols() is not supported in IE 11
  • Promise is not supported in Opera Mini all, IE Mobile 11, IE 11
  • Promise.race() is not supported in Opera Mini all, IE Mobile 11, IE 11
  • Promise.reject() is not supported in Opera Mini all, IE Mobile 11, IE 11
  • Promise.resolve() is not supported in Opera Mini all, IE Mobile 11, IE 11
  • Reflect is not supported in IE 11
  • Symbol.for() is not supported in IE 11
  • Symbol.iterator() is not supported in IE 11
  • Symbol.prototype() is not supported in IE 11
  • Symbol.species() is not supported in IE 11
  • Symbol.toPrimitive() is not supported in IE 11
  • Symbol.toStringTag() is not supported in IE 11
  • Uint8Array is not supported in IE Mobile 11

Frequently Asked Questions

How do I unset a default header

Simply set its value tonull,'', orundefined – and it will be unset and removed from the headers sent with your request.

A common use case for this is when you are attempting to useFormData and need the content boundary automatically added.

Why do my form uploads randomly fail with React Native

This is due to a bug with setting the boundary. For more information and temporary workaround if you are affected please seefacebook/react-native#7564 (comment).

Does this support callbacks, promises, or both

As of version1.0.0 we have dropped support for callbacks, it nowonly supports Promises.

What is thefetch method

It is a WHATWG browser API specification. You can read more about at the following links:

Does the Browser or Node.js supportfetch yet

Yes, a lot of browsers are now supporting it! See this reference for more informationhttp://caniuse.com/#feat=fetch.

If my engine does not supportfetch yet, is there a polyfill

Yes you can use thefetch method (polyfill) fromwhatwg-fetch ornode-fetch.

By default, React Native already has a built-infetch out of the box!

Can I makefetch support older browsers

Yes, but you'll need apromise polyfill forolder browsers.

What is this project about

Use this package as auniversal API wrapper for integrating your API in your client-side or server-side projects.

It's a better working alternative (and with less headaches; at least for me) – for talking to your API – thansuperagent and the defaultfetch Network method provide.

Use it for projects inNode,React,Angular,React Native, ...

It supports and istested for both client-side usage (e.g. with Bower, Browserify, or Webpack, withwhatwg-fetch) and also server-side (withnode-fetch).

Why not just usesuperagent orfetch

SeeBackground for more information.

Want to build an API back-end with Node.js

SeeLad as a great starting point, and read this article aboutbuilding Node.js API's with authentication.

Need help or want to request a feature

Filean issue on GitHub and we'll try our best help you out.

Tests

This package is tested to work withwhatwg-fetch andnode-fetch.

This means that it is compatible for both client-side and server-side usage.

Development

  1. Fork/clone this repository
  2. Runnpm install
  3. Runnpm run watch to watch thesrc directory for changes
  4. Make changes insrc directory
  5. Write unit tests in/test/ if you add more stuff
  6. Runnpm test when you're done
  7. Submit a pull request

Background

The docs suggest that you usesuperagent with React Native, but in our experience it did not work properly, therefore we went with the next best solution, the Githubfetch API polyfill included with React Native. After having several issues trying to usefetch and writing our own API wrapper for a project with it (and running into roadblocks along the way) – we decided to publish this.

Here were the issues we discovered/filed related to this:

We know that solutions likesuperagent exist, but they don't seem to work well with React Native (which was our use case for this package).

In addition, the authors of WHATWG's fetch API only support throwing errors instead of catching them and bubbling them up to the callback/promise (for example, with Frisbee any HTTP or API errors are found in theres.err object).

Therefore we createdfrisbee to serve as our API glue, and hopefully it'll serve as yours too.

Contributors

NameWebsite
Nick Baughhttp://niftylettuce.com/
Alexis Tyler
Assem-Hafez
Jordan Denison
James
Sampsa Saarela
Julien Moutte
Charles Soetan
Kesha Antonov
Ben Turley
Richard Evans
Hawken Rives
Fernando Montoya
Brent Vatne
Hosmel Quintana
Kyle Kirbatski
Adam Jenkins

Credits

License

MIT ©Nick Baugh


[8]ページ先頭

©2009-2025 Movatter.jp