public Map<String ,Object>index(ServletResponse res){
HttpServletResponse response = (HttpServletResponse)res
response.addHeader("Access-Control-Allow-Origin", "*")
response.addHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS")
response.addHeader("Access-Control-Allow-Credentials", "true")
response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token")
response.addHeader("Access-Control-Max-Age", "600000")
//TODO
...
}
这样就支持跨域了,但是这种方式不怎么安全,"Access-Control-Allow-Origin"后面的*代表支持所有域名。
代码如下,下面的代码实现了登陆校验,你可以写自己的拦截器
.config(function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider,$provide) {$urlRouterProvider
.otherwise('/')
$locationProvider.html5Mode(true)
$httpProvider.interceptors.push('authInterceptor')
})
.factory('authInterceptor', function($rootScope, $q, $cookies, $injector) {
var state
return {
// Add authorization token to headers
request: function(config) {
config.headers = config.headers || {}
if ($cookies.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('token')
}
return config
},
// Intercept 401s and redirect you to login
responseError: function(response) {
if (response.status === 401) {
(state || (state = $injector.get('$state'))).go('login')
// remove any stale tokens
$cookies.remove('token')
return $q.reject(response)
}
else {
return $q.reject(response)
}
}
}
})