Giter Site home page Giter Site logo

micro-cors's Introduction

CORS middleware for Micro

Summary

Simple CORS middleware for Zeit's Micro

CircleCI

We're working on v1, come help us out!

Install

yarn add micro-cors

Usage

Basic:

const { send } = require('micro')
const cors = require('micro-cors')()

const handler = (req, res) => send(res, 200, 'ok!')

module.exports = cors(handler)

With options:

const { send } = require('micro')
const microCors = require('micro-cors')
const cors = microCors({ allowMethods: ['PUT', 'POST'] })

const handler = (req, res) => send(res, 200, 'ok!')

module.exports = cors(handler)

Since the current version of micro-cors only sets headers in the response (res), you have do some manual work if you want to avoid triggering your handler on an OPTIONS preflight request (this will be built-in in v1). Let's say you want to approve preflight requests and otherwise only let POST requests trigger the handler:

const { send } = require('micro')
const cors = require('micro-cors')()

const handler = (req, res) => {
  if (req.method === 'OPTIONS') {
    return send(res, 200, 'ok!');
  }

  if (req.method !== 'POST') {
    throw createError(404, 'Not Found');
  }

  // handle incoming request as usual
}

module.exports = cors(handler)

Options

allowMethods

default: ['POST','GET','PUT','PATCH','DELETE','OPTIONS']

allowHeaders

default: ['X-Requested-With','Access-Control-Allow-Origin','X-HTTP-Method-Override','Content-Type','Authorization','Accept']

allowCredentials

default: true

exposeHeaders

default: []

maxAge

default: 86400

origin

default: *

micro-cors's People

Contributors

alexfreska avatar amio avatar andyburke avatar dependabot[bot] avatar dotcypress avatar elitan avatar evenchange4 avatar greenkeeper[bot] avatar infernalmaster avatar nrotta avatar pedronauck avatar possibilities avatar raineroviir avatar tim-phillips avatar timweprovide avatar xxzefgh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

micro-cors's Issues

code still runs even when cors complains

Am I missing something?

I have this code below:

const microCors = require('micro-cors')
const { send } = require('micro')

const cors = microCors({ origin: 'https://google.com' })

const handler = (req, res) => {
  console.log('> RUN')
  send(res, 200, 'OK')
}

module.exports = cors(handler)

If I make a request in the client-side I receive a cors warning in my console, but still the code inside handler runs, it's not blocked. If I'm not making a request from https://google.com, the code shouldn't run and I should receive a warning in the client-side, right?

Error when Content-Type header included

Getting

"Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."

when I include any Content-Type or Authorization header. Works when Content-Type and Authorization headers are omitted. Ideas?

Publish beta pre-release

Hi. Thank you for your work

I am interesting about publishing beta v1 pre-release

Current version does not allows to works without correct implementation of pre flight.
Pre flight implemented in #48 but did not published.

Currently I made a fork where built the lib and pushed it as a commit. That is added
as dependency to application. This way in not nice. Let me know any more good
way to install pre release v1 micro-cors library.

Thanks

Correctly use Vary header

  • We should set the Vary header to Origin iff dynamically setting the origin (i.e. origin is an array, regex, or function)
  • When setting the Vary header, make sure to append if there's already a value in res.headers['Vary'] and simply set if no value
  • add test('does not include Vary header for static origins')

Resources that wish to enable themselves to be shared with multiple Origins but do not respond uniformly with "*" must in practice generate the Access-Control-Allow-Origin header dynamically in response to every request they wish to allow. As a consequence, authors of such resources should send a Vary: Origin HTTP header or provide other appropriate control directives to prevent caching of such responses, which may be inaccurate if re-used across-origins.

https://www.w3.org/TR/cors/#resource-implementation

If CORS protocol requirements are more complicated than setting Access-Control-Allow-Origin to "*" or a static origin, Vary is to be used.

https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches

Not on npm?

Thanks for this module <3 Found the missing PATCH method bug on 0.0.4. It's fixed in master. npm publish recommended 👍

v1 - Bring us up to spec 🎉

In order to bring this library up to the CORS spec, we need to accomplish the following tasks. Please review the spec and add to this list!!

Simple Cross-Origin Request, Actual Request, and Redirects

  • If the Origin header in the request is not present, stop adding headers and run handler
  • If the Origin header in the request does not match exactly, stop adding headers and run handler
  • If allowCredentials is true, Set Access-Control-Allow-Origin to the value of the Origin header (is the client responsible for rejecting if Origin is *?)

Preflight Request

  • Return empty response and don't run the handler #48
  • Return 204 as empty response? Allow user to change response code?
  • If the Origin header in the request is not present, stop adding headers and return empty
  • If the Origin header in the request does not match exactly, stop adding headers and return empty

Dynamic Access-Control-Allow-Origin

  • Allow user to set multiple origins in config #53
  • Correctly use Vary header #58

Specification

Supplementary reading

cc @bukinoshita @infernalmaster @lemol

List request and request-promise as devDependencies

request and request-promise are listed as dependencies.
This leads to an unnecessary bloated package size when installing micro-cors.

  "dependencies": {
    "request": "^2.81.0",
    "request-promise": "^4.2.0"
  },

micros are supposed to be light!

Update npm module

Can you please update the code in npm, cors is eating the extra arguments in the current version but the one in github seems to be handling it correctly

Thanks

Cannot read property 'setHeader' of undefined

I see an already closed issue on this topic; I'm wondering what the solution to the problem is, and if there's something I am missing to get it to function correctly.

I am receiving this error after wrapping an axios.get request to a Google API endpoint.

Please publish an update to the NPM package

https://www.npmjs.com/package/micro-cors

The NPM package for this repo lists the most recent version as 0.1.1, but the version in this repo is 1.0.0. Is it possible to publish the newest version to NPM?

There are a lot of online tutorials that reference micro and micro-cors on the Internet. With this package not having been updated in 3 years, it is a cause for concern for new developers looking to adopt micro and a CORS solution in their applications.

The pre flight option request calls handler

The problem may be reproduced with apollo-server.

bundle.esm.js:169 OPTIONS http://localhost:3000/graphql 405 (Method Not Allowed)
project:1 Access to fetch at 'http://localhost:3000/graphql' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
index.js:75 [Network error]: TypeError: Failed to fetch

The ApolloServer does not expect http method OPTIONS here
So with the current implementation it is not possible to make it worked.

The pull #53 solves this problem here

code example in readme.md does not work

Both code does not work since send does not exist. It's pretty simple to solve that, but I do believe it would be better to have a code that actually works in the readme

const cors = require('micro-cors')()
const handler = (req, res) => send(res, 200, 'ok!')

module.exports = cors(handler)
const microCors = require('micro-cors')
const cors = microCors({ allowMethods: ['PUT', 'POST'] })
const handler = (req, res) => send(res, 200, 'ok!')

module.exports = cors(handler)

Error with microrouter

My code:

import micro from 'micro'
import auth from './auth'
import routes from './routes'
import cors from 'micro-cors'

micro(cors(auth(routes))).listen(3000)

then I get

TypeError: "string" must be a string, Buffer, or ArrayBuffer
    at Function.byteLength (buffer.js:441:11)

v1 not working due to babel

Why is version 1 based on babel? There's no strange code in it that needs to be transpiled. At the moment when the v1 is imported this error happens:

 ReferenceError: regeneratorRuntime is not defined

I'm also seeing that v1 is starving and I would be happy to help. Is there a list of issues I can work on? I can do some of the point in the spec, but some are question more than todos. Let me know.

No LICENSE file

The package.json says it is MIT licensed, but the actual LICENSE file is missing from the 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.