api-mount-client
by Vytenis Urbonavičius
api-mount-client provides a straightforward way for reaching back-end API served using api-mount-server or a compatible library.
Once setup, it makes it feel as if server-side API methods are called directly.
This library is based on api-link which is dedicating request functionality to either browser's fetch API or a node-fetch in a Node environment.
Installation
Consider using a more universal library - api-mount. api-mount contains both server and client code in one package. Usage and available methods are identical to api-mount-client. Only package name differs.
If you want to continue using a client-only version:
npm install --save api-mount-client
Usage
On your Node server build an object containing API methods (more information and alternative ways of constructing API are provided in the docs of api-mount-server):
In case your back-end is not based on Node but you would still want to use api-mount-client, you can explore Protocol section in the docs of api-mount-server.
Expose API via api-mount-server (see docs of api-mount-server to explore different approaches, usage of classes, namespacing, etc.):
ApiMount.exposeApiapi
In case you have client and server on different hosts/ports, you might run into browser's CORS policy restrictions. Unless handled requests may get blocked or responses may be incomplete. Below is an example using cors NPM package for working around browser's CORS policy constraint:
On client side (browser or Node client) mount the API:
If your API is namespaced, attach your namespace path to the baseUrl of mountApi:
Now you can access function on server from your client just like that:
Note that client always receives a Promise object. This is why await was used. In case foo rejects a promise or throws an exception, client will reject a promise with error as a payload.
Try it out!
In order to test library on vanilla JavaScript directly in browser, you can refer to this example:
Test
api-mount-client is exposed as a UMD library and therefore it is available in global scope if no other way of importing is available.
Above example assumes that API was exposed using Node code like this:
ApiMount.exposeApiapi
Supported Configuration
mountApi supports a configuration which contains following keys:
- baseUrl - base URL for HTTP requests. It may contain a protocol, host, port and base path but should not contain end-point method names and/or query arguments.
- fetchConfig - fetch API configuration which is passed through to the browser's fetch API or a server-side equivalent. Additional documentation can be found under /docs directory inside api-link package. One common case of using fetchConfig is to modify headers. Please note that provided headers completely override default ones. Please make sure that Content-Type is provided correctly. Normally it should be setup for JSON usage:
// ... fetchConfig: ,// ...