npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

api-mount-client

v1.0.13

Published

Library for making communication between front-end and back-end simple

Downloads

32

Readme

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):

const api = {
  foo() {
    return 'foo'
  },
}

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.):

const {apiMountFactory} = require('api-mount-server')
const ApiMount = apiMountFactory()
ApiMount.exposeApi(api)

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:

const ApiMount = apiMountFactory({
  beforeListen: app => {
    // This is just for testing purposes
    // You would probably want to explicitly list
    // where you expect requests to be coming from
    // for security reasons
    app.use(require('cors')())
  },
})

On client side (browser or Node client) mount the API:

import {mountApi} from 'api-mount-client'
const api = mountApi({baseUrl: 'http://someServer.com:3000'})

If your API is namespaced, attach your namespace path to the baseUrl of mountApi:

const api = mountApi({baseUrl: 'http://someServer.com:3000/api-name'})

Now you can access function on server from your client just like that:

const result = await api.foo() // 'foo'

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:

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script src="./node_modules/api-mount-client/dist/index.js"></script>
  </head>
  <body>
    <script>
      const api = window.ApiMountClient.mountApi({
        baseUrl: 'http://localhost:3000',
      })

      api.test().then(console.log)
    </script>
  </body>
</html>

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:

const {apiMountFactory} = require('api-mount-server')
var cors = require('cors')

const ApiMount = apiMountFactory({
  beforeListen: app => app.use(cors()),
})

const api = {
  test = () => 'works!',
}

ApiMount.exposeApi(api)

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: {
    requestInit: {
      headers: {
        'Content-Type': 'application/json',
        // Other headers may go here
      },
    },
  },
// ...