在每个主干同步请求中发送令牌 [英] Send token with every backbone sync request
问题描述
我的PHP api要求在我的前端Backbone应用程序的每个请求中提交用户令牌,以确保用户...
My PHP api requires a user token be submitted with every request from my front-end Backbone app to make sure the user...
- 处于活动状态
- 具有访问资源的权限
在Backbone中进行设置的最简单方法是什么?我猜唯一的方法是覆盖Backbone.sync,但是代码是什么样的呢?首选CoffeeScript.
What is the easiest way to set this up in Backbone? I am guessing the only way is to overwrite Backbone.sync, but what would the code look like? CoffeeScript preferred.
还有两件事
1.如果我得到一个403: Access Forbidden Error
,我想将用户重定向到/login
.
2.启动应用程序时,我从localStorage中提取了包含令牌的用户模型.
3.我有一个baseModel和baseCollection,所有模型/集合都来自
Two more things
1. I would like to redirect the user to /login
if I get a 403: Access Forbidden Error
2. I pull the user model which includes the token from localStorage when the app is bootstrapped
3. I have a baseModel and baseCollection which all models / collections come from
推荐答案
您可以执行以下操作:
var _sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
if( model && (method === 'create' || method === 'update' || method === 'patch') ) {
options.contentType = 'application/json';
options.data = JSON.stringify(options.attrs || model.toJSON());
}
_.extend( options.data, {
"access_token": "some-token"
});
return _sync.call( this, method, model, options );
}
然后仅监听fetch/save方法的失败事件即可将用户重定向到/login
And just listen for the fail event of fetch/save method to redirect a user to /login
model.fetch().fail( /* redirect */ )
这篇关于在每个主干同步请求中发送令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!