前言
前端用什么框架都可以,这里选择小巧的vuejs。
要实现的功能很简单:
2、使用带token的header访问服务器的一个资源
本次实验环境:
css-loader": "^0.25.0","file-loader": "^0.9.0","vue-loader": "^11.1.4","vue-template-compiler": "^2.2.1","webpack": "^2.2.0","webpack-dev-server": "^2.2.0"
}
开发IDE:Atom
首先建一个项目
使用webpack构建
安装插件
/Atom/vue-jwt-demo# cnpm install vue-resource
整体目录
auth.js
完成token的存取
export default{
data:{
authenticated:false
},login(context,info){
context.$http.post(LOGIN_URL,info).then(function(data){
console.log(data.bodyText)
localStorage.setItem('token',data.bodyText);
this.authenticated = true
//跳到home页
this.$router.push('home')
},function(err){
console.log(err+","+err.body.message)
context.error = err.body.message
})
},getAuthHeader(){
return {
'Authorization':'Bearer '+localStorage.getItem('token')
}
},checkAuth(){
var token = localStorage.getItem('token')
if(token){
this.authenticated = true
}else{
this.authenticated = false
}
}
}
data:{
authenticated:false
},login(context,info){
context.$http.post(LOGIN_URL,info).then(function(data){
console.log(data.bodyText)
localStorage.setItem('token',data.bodyText);
this.authenticated = true
//跳到home页
this.$router.push('home')
},function(err){
console.log(err+","+err.body.message)
context.error = err.body.message
})
},getAuthHeader(){
return {
'Authorization':'Bearer '+localStorage.getItem('token')
}
},checkAuth(){
var token = localStorage.getItem('token')
if(token){
this.authenticated = true
}else{
this.authenticated = false
}
}
}
main.js
程序入口:完成路由和初始化
Vue.use(VueRouter)
Vue.use(VueResource)
Vue.use(VueResource)
//在启动APP时进行校验是否有token
auth.checkAuth()
const routes= [
{
path:'/',redirect:'/login'
},{
path:'/login',component:Login
},{
path:'/home',component:Home
}
]
const router = new VueRouter({
routes
})
new Vue({
router,render: h => h(App)
}).$mount('#app')
App.vue
页面载体
{{msg}}
Login.vue
效果:丑是丑了点
Home.vue
{{msg}}
对应在服务端:
可看到浏览器的本地存储:
原文链接:https://www.f2er.com/vue/39056.html