问题描述
我正在开发与AngularJS前端和后端的Rails Web应用程序。
I'm developing a web application with an AngularJS frontend and a Rails backend.
我的目标是保持两个完全独立的,因为Rails应用程序将最终沦为一个简单的REST服务器,AngularJS前端将只是使用后端几个不同的客户之一。出于这个原因,我不想给前端集成到Rails的资产管道,或者类似的。
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.
Rails应用程序在端口3000上本地运行的前端使用编译静态资产,的,它包含了我在3001端口上运行的开发服务器。
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.
有关发展的目的,我怎么能得到AngularJS应用谈Rails服务器,通过角度的的服务?
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.
我只需要建立CORS的Rails应用程序?有另一种方式 - 也许某种本地hosts文件伎俩(我是Mac,FWIW上)或类似的?我问,因为我的同事负责Rails应用程序(我有限的使用Rails的经验),但出城了一会儿;我的知识大多局限于我已经设置了AngularJS堆栈。
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.
感谢您的帮助!
推荐答案
啊,太好了。这里有几个解决方案:
Ah, wonderful. Here are a few solutions:
- 设置了CORS,这应该不是太难。所有你需要做的就是将头添加到您的服务静态内容(而不是铁轨REST端点)页,这个问题是你真的不应该那样做,除非你有一个很好的理由(故见3)。你是如何服务于静态内容?应该有插件来为你做的头文件,如果它是一个流行的工具
- 服务从导轨后端angularJS页,现在(使用某种静态路由)
- 如果您正在考虑生产,并希望排序了这一点为好,使用nginx代理两个服务为一体的单域,的
- 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
- serve the angularJS pages from the rails backend for now (using some kind of static route)
- 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
这篇关于如何使从不同端口上运行的本地应用程序AngularJS请求当地的Rails应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!