问题描述
我的 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 */ )
这篇关于随每个骨干网同步请求发送令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!