前後端分離之VueJS前端,端分離之VueJS

來源:互聯網
上載者:User

前後端分離之VueJS前端,端分離之VueJS

本節接上一篇部落格:前後端分離之Java後端

代碼:https://github.com/jimolonely/vue-jwt-demo

前言

前端用什麼架構都可以,這裡選擇小巧的vuejs。

要實現的功能很簡單:
1、登入功能,成功將伺服器返回的token存在本地
2、使用帶token的header訪問伺服器的一個資源

本次實驗環境:

"dependencies": {    "vue": "^2.2.1"  },  "devDependencies": {    "babel-core": "^6.0.0",    "babel-loader": "^6.0.0",    "babel-preset-latest": "^6.0.0",    "cross-env": "^3.0.0",    "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 init webpack-simple vue-jwt-demo.../Atom# cd vue-jwt-demo//Atom/vue-jwt-demo# cnpm install/Atom/vue-jwt-demo# npm run dev

安裝外掛程式

/Atom/vue-jwt-demo# cnpm install vue-router/Atom/vue-jwt-demo# cnpm install vue-resource

整體目錄

auth.js

完成token的存取

const SERVER_URL = 'http://localhost:8081'const LOGIN_URL = SERVER_URL+'/login2'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        }    }}
main.js

程式入口:完成路由和初始化

import Vue from 'vue'import App from './App.vue'import Login from './component/Login.vue'import Home from './component/Home.vue'import VueRouter from 'vue-router'import VueResource from 'vue-resource'import auth from './auth/auth'Vue.use(VueRouter)Vue.use(VueResource)//在啟動APP時進行校正是否有tokenauth.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

頁面載體

<template>  <div id="app">    <h1>{{msg}}</h1>    <router-view></router-view>  </div></template><script>export default {  name: 'app',  data () {    return {      msg: 'Vue前後端分離demo'    }  }}</script>
Login.vue

登入頁面

<template>  <div>    <h2>登入</h2>    <p>{{ error }}</p>    <div>      <input        type="text"        placeholder="Enter your username"        v-model="info.username"      >    </div>    <div>      <input        type="password"        placeholder="Enter your password"        v-model="info.password"      >    </div>    <button @click="submit()">登入</button>  </div></template><script>import auth from '../auth/auth'export default {  data() {    return {      info: {        username: '',        password: ''      },      error: ''    }  },  methods: {    submit() {      var info = {        username: this.info.username,        password: this.info.password      }      auth.login(this, info)    }  }}</script>

效果:醜是醜了點

Home.vue

首頁面,訪問一個擷取郵箱的請求

<template>  <div id="home">    <h1>{{msg}}</h1>    <button @click="getEmail()">Get Email</button>    <h2>Email:{{email}}</h2>  </div></template><script>import auth from '../auth/auth'export default {  name: 'home',  data () {    return {      msg: '歡迎您登入成功',      email:''    }    },    beforeCreate(){        //如果沒有token的話需要重新登入         if(!auth.authenticated){            this.$router.push('login')        }    },    methods:{        getEmail(){            this.$http.get('http://localhost:8081/user/getEmail',{                headers:auth.getAuthHeader()            }).then(function(re){                this.email = re.bodyText            },function(){                console.log("get email error")            })        }    }}</script><style>#app {  font-family: 'Avenir', Helvetica, Arial, sans-serif;  -webkit-font-smoothing: antialiased;  -moz-osx-font-smoothing: grayscale;  text-align: center;  color: #2c3e50;  margin-top: 60px;}h1, h2 {  font-weight: normal;}a {  color: #42b983;}</style>

對應在服務端:

@GetMapping("/getEmail")    public String getEmail() {        return "xxxx@qq.com";    }

可看到瀏覽器的本機存放區:

參考:
https://github.com/auth0-blog/vue-jwt-authentication(基於vue1.x)
https://router.vuejs.org/zh-cn/essentials/getting-started.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.