While building web applications, I sometimes run into the case where my http requests fail because the web server does not support Cross-origin resource sharing or CORS. One way to workaround this by using a http proxy which adds the missing CORS header to the response. This can be easily done with Node.js and the http-proxy library. Here is the script that will create a proxy that listens on port 8000, proxies each HTTP request to localhost:8042 and return the response with the CORS header added:
var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({target:'http://localhost:8042'}).listen(8000);
proxy.on('proxyRes', function(proxyReq, req, res, options) {
// add the CORS header to the response
res.setHeader('Access-Control-Allow-Origin', '*');
});
proxy.on('error', function(e) {
// suppress errors
});
You can also workaround this by disabling CORS in your browser. For example, chrome can be started with the --disable-web-security flag.
Useful Article on CORS
ReplyDeleteNode.js Training
note: "proxy.on('proxyRes', function(proxyReq, req, res, options)" should read "proxy.on('proxyRes', function(proxyRes, req, res, options)", note "proxyRes" instead of "proxyReq"
ReplyDeletehow and where to apply this code?
ReplyDelete