Giter Site home page Giter Site logo

koa-jsonp's Introduction

@hitokoto/koa-jsonp

js-standard-style Node.js CI NPM version NPM downloads GitHub Stars License

A koajs streaming friendly JSONP middleware that supports GET/POST JSONP requests.

Install

$ npm install @hitokoto/koa-jsonp

Example

const db = require('nano')('http://localhost:5984/my_db')
const stringify = require('json-array-stream')
const jsonp = require('koa-jsonp')

app.use(jsonp())

app.use(mount('/users', async function (ctx) {
  ctx.type = 'json'
  ctx.body = db.view('koa_example', 'users')
    .pipe(JSONStream.parse('rows.*.value'))
    .pipe(stringify())
}))

app.use(mount('/dow', async function (ctx) {
  ctx.body = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
}))

app.listen(8080)

yield

GET  http://localhot:8080/users                       -> JSON
POST http://localhot:8080/users                       -> JSON
GET  http://localhot:8080/users?callback=onUserList   -> JSONP
POST http://localhot:8080/users?callback=onUserList   -> JSONP

GET  http://localhot:8080/dow                         -> JSON
POST http://localhot:8080/dow                         -> JSON
GET  http://localhot:8080/dow?callback=dowReady       -> JSONP
POST http://localhot:8080/dow?callback=dowReady       -> JSONP

API

function jsonp (options)

Returns the koa middleware.

Options

  • domain - (String: defaults to '.default.lan') the first level domain where your API will be consumed. Used in iframe mode (???)
  • callbackName: (String: defaults to 'callback') The name of the JSONP callback

Use cases

  • JSONP: text/javascript
  • JSONP + iFrame: text/html

The middleware auto selects the right format based on the presence of callback (querystring) and the HTTP method.

table

JSONP CORS

This is not required if your frontend and your API run in the same domain or if you set the Access-Control-* headers properly. In this case just use an XMLHttpRequest and don't use this middleware at all. Reference: MDN - HTML5Rocks - SO

There is a way to read a JSONP response after sending a POST request (form) in the browser. The solution is to set an iframe as target of the form (could be hidden). The iframe will load your response page, in this case plain HTML with a script tag and will call your callback using parent.callbackname(data).

This is an old snippet using mootools that creates a form, an iframe, and posts your request. Then dispose everything after executing your callback. You can easily port it to jQuery.

var __requestsMap__ = {}

function post(url, fields, callback) {
  var requestId = new Date().getTime()
  var inputs = []

  Object.keys(fields).forEach(function (fieldName) {
    inputs.push(new Element('input', {
      name: fieldName,
      value: data[fieldName]
    }))
  })

  if (url.match(/\?/)) {
    url += '&callback=__requestsMap__["' + requestId + '"]'
  } else {
    url += '?callback=__requestsMap__["' + requestId + '"]'
  }

  var form = new Element('form', {
    'enctype': enctype,
    'method': 'post',
    'action': url,
    'target': requestId,
    'style': 'display: none'
  }).adopt(inputs).inject(document.body)

  var iframe = new Element('iframe', {
    id: requestId,
    name: requestId,
    styles: { display: 'none' }
  }).inject(document.body)

  __requestsMap__[requestId] = function (response) {
    callback(null, response)
    // cleanup
    delete __requestsMap__[requestId]
    iframe.dispose().destroy()
    form.dispose().destroy()
  }

  form.submit()
}

How to contribute

koa-jsonp follows (more or less) the Felix's Node.js Style Guide, your contribution must be consistent with this style.

The test suite is written on top of mochajs/mocha and it took hours of hard work. Please use the tests to check if your contribution is breaking some part of the library and add new tests for each new feature.

⚡ npm test

License

This software is released under the MIT license cited below.

Copyright (c) 2013 Kilian Ciuffolo, [email protected]. All Rights Reserved.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the 'Software'), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

koa-jsonp's People

Contributors

a632079 avatar dependabot-preview[bot] avatar dependabot[bot] avatar greenhat616 avatar kilianc avatar renovate-bot avatar tj avatar

Watchers

 avatar

Forkers

lovechen

koa-jsonp's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm eslint-plugin-node Available
npm eslint-plugin-standard Unavailable
npm request Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update dependency chai to v5
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency eslint-config-standard to v17
  • chore(deps): update dependency eslint-plugin-html to v8
  • chore(deps): update dependency eslint-plugin-promise to v6
  • chore(deps): update dependency eslint-plugin-standard to v5
  • chore(deps): update dependency mocha to v10
  • chore(deps): update dependency standard to v17
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/node.js.yml
  • actions/checkout v2
  • actions/setup-node v1
.github/workflows/npm-publish.yml
  • actions/checkout v2
  • actions/setup-node v1
  • actions/checkout v2
  • actions/setup-node v1
npm
package.json
  • iconv-lite ^0.6.2
  • JSONStream 1.3.5
  • chai 4.2.0
  • eslint 7.10.0
  • eslint-config-standard 14.1.1
  • eslint-plugin-html 6.1.0
  • eslint-plugin-import 2.22.1
  • eslint-plugin-node 11.1.0
  • eslint-plugin-promise 4.2.1
  • eslint-plugin-standard 4.0.1
  • json-array-stream 0.1.2
  • koa 2.13.0
  • koa-mount 4.0.0
  • mocha 8.1.3
  • request 2.88.2
  • server-destroy 1.0.1
  • standard 14.3.4
travis
.travis.yml
  • node 14

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.