【发布时间】:2015-01-07 11:03:20
【问题描述】:
我仅在生产环境中的 cmets 控制器上收到以下错误(在开发中工作正常)。用户流程如下:我有 jQuery,它在按下特定按钮时运行,它呈现部分文件以添加新注释,一个简单的表单。控制器中 .js 请求的 respond_to 方法用于 new.js.erb 文件。这应该相对容易做到,但是 Rails(我使用的是 Rails 4.1.1)代码或我的服务器(Rackspace 云服务器)出现了问题。错误如下:
CommentsController#new 中的 ActionController::InvalidCrossOriginRequest 安全警告:另一个站点上的嵌入标签请求受保护的 JavaScript。如果您知道自己在做什么,请继续禁用此操作的伪造保护以允许跨域 JavaScript 嵌入。
我在我的 cmets 控制器中尝试了以下代码(不起作用)。它只是将浏览器中的 .js 文件呈现为文本字符串(javascript 不起作用)。
protect_from_forgery except: :new
skip_before_action :verify_authenticity_token
我尝试在 application_controller.rb 文件中使用: :exception 方法删除protect_from_forgery,但它不起作用(只是将浏览器中的javascript呈现为文本字符串)。
我尝试将“protect_from_forgery with::exception”替换为“protect_from_forgery with::null_session”,但这也不起作用(给出与上述相同的 InvalidCrossOriginRequest 错误)。
我没有办法解决这个问题。同样,它只发生在生产中。在我的本地机器上(通过 localhost),一切正常。我的 cmets 控制器的代码如下:
class CommentsController < ApplicationController
# before_action :set_comment, only: [:show, :edit, :update, :destroy]
before_action :load_topic
before_action :authenticate_user!
# protect_from_forgery except: :new
# skip_before_action :verify_authenticity_token
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
@comment = Comment.new
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
@comment = @topic.comments.new(comment_params)
@comment.user_id = current_user.id
respond_to do |format|
if @comment.save
format.html { redirect_to @topic, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
format.js
else
format.html { redirect_to @article, alert: 'Unable to add comment' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
format.js { render 'fail_create.js.erb'}
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { render :show, status: :ok, location: @comment }
else
format.html { render :edit }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment = @topic.comments.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to @topic, notice: 'Comment was successfully deleted.' }
format.json { head :no_content }
format.js
end
end
private
def load_topic
@topic = Topic.find(params[:topic_id])
end
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:topic_id, :body, :name)
end
end
任何有关解决此问题的建议将不胜感激。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 xss csrf