我使用AngularJS for Rails应用程序开发客户端,我坚持使用authenticity_token。
以下是我的服务的样子:
blog_app.factory('AuthenticityToken', ['$http', '$q',
($http, $q) ->
() ->
delay = $q.defer()
$http.get('/authenticity_token').success(
(data) ->
delay.resolve(data.authenticity_token)
).error(
->
delay.reject('Can\'t get authenticity_token')
)
return delay.promise
])
post_services.factory('Post', ['$resource',
($resource) ->
$resource('/posts/:id', {id: '@id'},
{
query: {
method: 'GET',
params: {limit: 10, order: 'desk'},
isArray: false
}
}
)
])
如何在 Post 中注入并解析 AuthenticityToken ,这样我就可以在 Post 的默认参数中使用真实性令牌?< / p>
相反,我只能为控制器解析它:
angular.module('posts', ['posts.services']).config(
['$routeProvider', ($routeProvider) ->
$routeProvider
.when('/posts', {
templateUrl: '/pages/posts/',
controller: 'ListCtrl',
resolve: {
authenticity_token: ['AuthenticityToken', (AuthenticityToken) ->
AuthenticityToken()
]
}
})
]
)
然后明确传递给发布资源
答案 0 :(得分:1)
angular.module('posts', ['posts.services']).config(
['$routeProvider', '$httpProvider', ($routeProvider, $httpProvider) ->
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json'
$httpProvider.defaults.headers.put['Content-Type'] = 'application/json'
token = $("meta[name='csrf-token']").attr("content")
$httpProvider.defaults.headers.post['X-CSRF-Token'] = token
$httpProvider.defaults.headers.put['X-CSRF-Token'] = token
$httpProvider.defaults.headers.common['X-CSRF-Token'] = token
$routeProvider
.when('/posts', {
templateUrl: '/pages/posts/',
controller: 'ListCtrl'
})
]
)