Grunt has a module grunt-connect-proxy that exists to help to solve this issue. It delegates requests that match a given URL to the backend of your choice. So for example, you want to access your backend using the URL http://localhost:8080/api, you can write a proxy rule so that whenever your user tries to access this URL in a browser, the proxy will get the data from your backend and server it at this particular URL.
The procedure to setup the Grunt proxy for backend requests is simple. First, you will have to add the proxy configuration to your Gruntfile.js. In this example, I am assuming that the backend server is running on the port 8000 and the Grunt server is running on the port 8080. This configuration will delegate all requests to http://localhost:8080/api to http://localhost:8000/backend.
Now register your Grunt server task to run the proxy on Grunt execution.
Let me explain, the above two scripts line by line. In the connect section of your Gruntfile, we add a new section called proxies. The options defined in the proxies section are explained below.
More options can be found in the documentation of grunt-connect-proxy.
You will also need to setup the proxy's middleware in the options section of the connect. The relevant code is as follows.
Finally, include your proxy task in the server task. It is necessary to append the proxy task before the connect task. Also, make sure to specify the connect target in the configureProxies section. In our case, the connect target is the server.
Now you can start your Grunt server via this configured proxy by typing Grunt server in the command line. You should see something like this in the console.
The above output confirms that the proxy is working fine. Some of the example URLs are:
That's all. Now you will not face any problems getting data from any backend of your choice.