[FrontEnd] Make Requests CORS compatible

How to make middle requests CORS? If you are a industry veteran, one would say”JSONP”, that’s fine, but so old-time. Now its time to learn something new.

Introducing a proper way of solving it.

Background:

Now, we just need to implement. What really what we need to do just the following:

UI, Ajax setup

$.ajaxSetup({
type: "POST",
data: {},
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
});

API (Backend) Example: Express (Nodejs)

app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.get('Origin') || '*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
res.header('Access-Control-Expose-Headers', 'Content-Length');
res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
if (req.method === 'OPTIONS') {
return res.send(200);
} else {
return next();
}
});

Since you know what’s under the hood, and there are some middle layers you can use without re-invent the wheels:

  1. Express CORS
  2. Flask CORS

Flask (Python)

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, support_credentials=True)
@app.route("/login")
@cross_origin(supports_credentials=True)
def login():
return jsonify({'success': 'ok'})
if __name__ == "__main__":
app.run(host='local-host', port=8000, debug=True)

Reference

  1. How to enable CORS on express.js 4.x on all files
  2. How to: enable CORS in express.js