Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add CORS example

  • Loading branch information...
commit 0f20a5e06af75c07ab92b3a2266e4021acd053d1 1 parent 56bfb92
@tj tj authored
Showing with 57 additions and 0 deletions.
  1. +45 −0 examples/cors/index.js
  2. +12 −0 examples/cors/public/index.html
View
45 examples/cors/index.js
@@ -0,0 +1,45 @@
+
+/**
+ * Module dependencies.
+ */
+
+var express = require('../..')
+ , app = express()
+ , api = express();
+
+// app middleware
+
+app.use(express.static(__dirname + '/public'));
+
+// api middleware
+
+api.use(express.logger('dev'));
+api.use(express.bodyParser());
+
+/**
+ * OPTIONS for all routes.
+ */
+
+api.all('*', function(req, res, next){
+ // use "*" here to accept any origin
+ res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
+ res.set('Access-Control-Allow-Methods', 'GET, POST');
+ res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
+ // res.set('Access-Control-Allow-Max-Age', 3600);
+ next();
+});
+
+/**
+ * POST a user.
+ */
+
+api.post('/user', function(req, res){
+ console.log(req.body);
+ res.send(201);
+});
+
+app.listen(3000);
+api.listen(3001);
+
+console.log('app listening on 3000');
+console.log('api listening on 3001');
View
12 examples/cors/public/index.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html>
+ <body>
+ <script>
+ var req = new XMLHttpRequest;
+ req.open('POST', 'http://localhost:3001/user', false);
+ req.setRequestHeader('Content-Type', 'application/json');
+ req.send('{"name":"tobi","species":"ferret"}');
+ console.log(req.responseText);
+ </script>
+ </body>
+</html>
Please sign in to comment.
Something went wrong with that request. Please try again.