基本的HTTP身份验证不包括标题中的JSON? (Backbone.js到Rails Server)
-
11-10-2019 - |
题
我正在使用Backbone.js使用JSON API为我的Rails应用程序创建纯JS前端。
Backbone.js模型URL看起来像这样:
window.MedicationCollection = Backbone.Collection.extend({
model: Medication,
url: 'http://localhost:3000/medication_options'
});
Crud可以很好地工作。它使用“应用程序/JSON”内容类型将请求发送到我的服务器。
但是我需要为API添加身份验证,而我的Rails应用程序正在使用Authlogic,因此我添加了此验证:
before_filter :require_user
def require_http_auth_user
return true if current_user
authenticate_or_request_with_http_basic do |email, password|
email = email.gsub("_at_", "@") if email.include?("_at_")
if @current_user = User.find_by_email(email)
@current_user.valid_password?(password)
else
false
end
end
end
铁轨中的典型CRUD方法看起来像这样:
def update
@medication_option = MedicationOption.find(params[:id])
if @medication_option.update_attributes(params[:medication_option])
flash[:notice] = "Successfully updated medication."
end
respond_with @medication_option
end
因此,在我的backbone.js模型中,我在URL中添加了“用户名:密码”:
window.MedicationCollection = Backbone.Collection.extend({
model: Medication,
url: 'http://username:password@localhost:3000/medication_options'
});
身份验证可以与适当的凭证合适,但是由于某些原因,所有骨干。JS请求由Rails Server解释为HTML而不是JSON。
由于某种原因,在基本的HTTP身份验证期间,JSON标头丢失了。
因此,如果我明确地将“ .json”添加到URL的末尾:
window.MedicationCollection = Backbone.Collection.extend({
model: Medication,
url: 'http://username:password@localhost:3000/medication_options.json'
});
我可以得到基本的工作请求。
但是,当我确实毫无用处时,它不起作用,因为它将ID附加到URL的末端,因此错误:
ActionController::RoutingError (No route matches "/medication_options.json/41516")
所以我不确定从这里去哪里。
解决方案
您的.json应该始终处于URL的末尾,以解释为JSON:
/medication_options/41516.json
您可以在需要将JSON放置在正确的位置的情况下编辑模型URL以及集合URL。
根部问题是为什么首先不会将其处理为JSON。如果您使用的是Rails 3,您有:
respond_to :js
或者
respond_to :json
要匹配您的响应_并确保您的控制器接受这种格式(否则,默认情况下,Rails会返回406错误)?
其他提示
我从未使用过文档。 url
并返回函数的结果,而不是给它一个文字字符串值。你能添加 .json
以这种方式到达URL字符串的末端?
尝试这样的事情:
_.extend(Medication,
{extension:'.json',
url:function() {
var base = getUrl(this.collection);
if (this.isNew()) return base + this.extension;
return (base + (base.charAt(base.length - 1) == '/' ? '' : '/')
+ this.id + this.extension);
}
});
不隶属于 StackOverflow