Last Updated: February 25, 2016
·
3.816K
· poupougnac

Allow cross-domain requests (CORS) with Express 3

This script use CoffeeScript, if you want plain javascript :
http://js2coffee.org

allowCrossDomain is a middleware function that allows AJAX requests coming from an other domain. Here is a typical configuration for an API.

allowCrossDomain = (req, res, next) ->
    res.header 'Access-Control-Allow-Origin', '*'
    res.header 'Access-Control-Allow-Methods', 'GET'
    res.header 'Access-Control-Allow-Headers', 'Content-Type'
    next()

app.use allowCrossDomain

Instead of "*", you can set a specific domain.

If you have several domains, there are several methods : http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains

Have a fresh tip? Share with Coderwall community!

Post
Post a tip