我有一个 Rails 3.1 应用程序,它使用 devise 进行身份验证。我正在尝试通过 ajax 调用 url。由于某种原因,我不断收到 401 未经授权的访问。我已经按照这里的教程http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery进行操作关于如何验证 jQuery 请求。请求的代码是
$.get('/chromosomes.json', {sequence_start: '10', sequence_end: '100'},
function(data){
alert(data)
}, 'json');
奇怪的是我在服务器上看到
于 2011 年 11 月 10 日星期四 15:51:33 -0500 开始获取 127.0.0.1 的“/chromosomes.json?sequence_start=10&sequence_end=100&_=1320958293654” 由 ChromosomesController#index 作为 JSON 进行处理 参数:{“sequence_start”=>“10”,“_”=>“1320958293654”,“sequence_end”=>“100”} 10 毫秒内完成
在我的 Controller 中,我有:
before_filter :authenticate_user!
def index
respond_to do |format|
format.html
format.json { render :json => @chromosomes }
end
end
由于某种原因,真实性 session token 没有传递到 Rails。如果我删除authenticate_user!在过滤之前它工作正常!?很感谢任何形式的帮助。谢谢!
最佳答案
我通过将 :token_authenticatable 添加到我的用户模型中解决了这个问题。这允许通过 session token 对用户进行身份验证。
关于Rails 3 中的 jQuery Ajax 调用收到 401 未经授权的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086170/