-
Notifications
You must be signed in to change notification settings - Fork 17
How to setup a proxy to avoid CORS issues
The build process uses the following grunt plugins:
- grunt-contrib-connect (Connect)
- grunt-connect-proxy (Proxy)
Out of the box, you can run your generated app with 'grunt serve'. This will not only serve your app but will watch for file changes (linting your code) and also setup live-reload so you can watch code changes (on save) live in your browser.
Connect enables a simple Node.js web server to serve your generated app. It includes a middleware extension concept that allows you to intercept the request and response to do things like setup a proxy (grunt-connect-proxy helps) or add http headers (e.g. CORS headers).
This is what is automatically scaffolded into your Gruntfile.js when you execute the generator by default:
connect: {
options: {
port: 8080,
livereload: 35729,
hostname: "localhost",
base: "."
}
}
This enables connect to serve your app at http://localhost:8080.
If, for example you wish to use an OData service in your app that is in another domain you will likely run into CORS issues. To get around this during development we can add a simple proxy to the Connect server. See the Gruntfile.js config below as an example:
connect: {
options: {
port: 8080,
livereload: 35729,
hostname: "localhost",
base: "."
},
proxies: {
context: "/Northwind", // When the url contains this...
host: "services.odata.org", // Proxy to this host
changeOrigin: true
},
livereload: {
options: {
middleware: function(connect, options) {
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
// Setup the proxy
var middlewares = [require("grunt-connect-proxy/lib/utils").proxyRequest];
// Serve static files.
options.base.forEach(function(base) {
middlewares.push(connect.static(base));
});
return middlewares;
}
}
}
}
Here we are using grunt-connect-proxy as middleware to proxy any resources containing the path /Northwind to the http://services.odata.org:80 host. No more CORS issues!!
tbd...