Rails 无效的跨源请求

Rails InvalidCrossOriginRequest

我的 Rails 应用程序的一个页面上有一个 remote: true link,它调用同一页面的 .js 版本,然后运行一个脚本来更新页面内容到位。

它工作正常,但从昨天开始,我现在每次单击其中一个 link 时都会得到 Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.

关于如何阻止它的任何想法?

将其添加到呈现页面片段的控制器中

class FooController < ApplicationController
    protect_from_forgery except: :index

其中 index 是您要跳过此保护的操作的名称


Cross-Origin 政策

您收到的错误是因为所谓的 Cross-Origin 政策。它是每个浏览器中的标准,不允许页面使用来自其他域的 运行 脚本。解决这个问题的方法是在 http 请求中添加 header 允许您的内容在其他域中是 运行。

维基百科对此有解释:

The second technique for relaxing the same-origin policy is standardized under the name Cross-Origin Resource Sharing. This standard extends HTTP with a new Origin request header and a new Access-Control-Allow-Origin response header. It allows servers to use a header to explicitly list origins that may request a file or to use a wildcard and allow a file to be requested by any site. Browsers such as Firefox 3.5, Safari 4 and Internet Explorer 10 use this header to allow the cross-origin HTTP requests with XMLHttpRequest that would otherwise have been forbidden by the same-origin policy.

http://en.wikipedia.org/wiki/Same-origin_policy