How to make requests to a local Rails app from a local AngularJS app running on a different port?

情到浓时终转凉″ 提交于 2019-12-23 05:13:16

问题


I'm developing a web application with an AngularJS frontend and a Rails backend.

My goal is to keep the two entirely separate, since the Rails app will ultimately be relegated to a simple REST server, and the AngularJS frontend will be just one of a few different clients that use the backend. For that reason, I don't want to integrate the frontend into the Rails asset pipeline, or similar.

The Rails app is running locally on port 3000. The frontend uses Gulp to compile static assets, and BrowserSync, which contains a development server that I'm running on port 3001.

For development purposes, how can I get the AngularJS app to talk to the Rails server, avoiding this browser error (which I'd expected) when making HTTP request via Angular's $http service?

No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3001' is therefore not allowed access.

Do I just need to set up CORS in the Rails app? Is there another way - maybe some sort of local hosts file trick (I'm on a Mac, FWIW) or similar? I ask because my coworker is responsible for the Rails app (I have limited experience with Rails) but is out of town for a while; my knowledge is mostly limited to the AngularJS stack that I've set up.

I've searched and read up for about an hour, but haven't yet been able to find anything that I can grok that is applicable to my situation. I might not be aware of the best search terms.

Thanks for any help!


回答1:


Ah, wonderful. Here are a few solutions:

  1. set up CORS, which shouldn't be too hard. All you have to do is add the headers to pages serving your static content (not the rails REST endpoints), The problem with this is you shouldn't really be doing it unless you have a good reason (so see 3). How are you serving the static content? There should be plugins to do the headers for you if it's a popular tool
  2. serve the angularJS pages from the rails backend for now (using some kind of static route)
  3. if you're thinking about production and want to sort this out for good, use nginx to proxy the two services into one single domain, http://nginx.org/en/docs/beginners_guide.html


来源:https://stackoverflow.com/questions/27674792/how-to-make-requests-to-a-local-rails-app-from-a-local-angularjs-app-running-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!