登陸驗證,獲取token
methods:{callApi () {var vm = thisvm.msg = ''vm.result = ''//驗證地址vm.loginUrl= 'http://xxx/'//查詢地址vm.apiUrl = 'http://yyy/'vm.loginModel= {username: '你的用戶名',password: '你的密碼',// grant_type: 'password', }//先獲取 token axios.post(vm.loginUrl,vm.loginModel).then(function(res){sessionStorage.setItem('accessToken', res.data.token)//顯示token值 console.log(res.data.token);}).catch(function(err){console.log(err);});
? 查詢數據:
// 執行api 訪問*/ axios.get(vm.apiUrl,{//獲取token ,拼裝jwt后寫入消息頭 headers//注意:jwt后面有個空格 ,jwt 是配合 django 的 rest_framework_jwt headers:{ Authorization:'JWT ' + sessionStorage.getItem('accessToken')}}).then(function(res){// 顯示結果 console.log(res.data);}).catch(function(err){console.log(err);})
?完整代碼:
<template> <div id="SurveyForm"><div ><form id="transForm" v-on:submit="formSubmit"><p>題目</p><h2> {{Title}}</h2><br><br>請選擇:<select v-model="Selected"><option value="5">5</option><option value="4">4</option><option value="3">3</option><option value="2">2</option></select><input type="submit" value="提交"></form><div class="container"><div class="form-group"><label></label><button @click="callApi">開始</button></div><div class="result">API調用結果:{{ result | json }}</div></div></div></div> </template><script> import axios from 'axios';export default {name: "SurveyForm", data:function(){return {Title:"題目一",Selected: "5"}},result: '',methods:{callApi () {var vm = thisvm.msg = ''vm.result = ''//驗證地址vm.loginUrl= 'http://xxx/api/auth/'//查詢地址vm.apiUrl = 'http://xxx/api/surveysn/'vm.loginModel= {username: 'xxx',password: '***',// grant_type: 'password', }//先獲取 token axios.post(vm.loginUrl,vm.loginModel).then(function(res){sessionStorage.setItem('accessToken', res.data.token)//顯示token值 console.log(res.data.token);}).catch(function(err){console.log(err);});// 執行api 訪問*/ axios.get(vm.apiUrl,{//獲取token ,拼裝jwt后寫入消息頭 headers//注意:jwt后面有個空格 ,jwt 是配合 django 的 rest_framework_jwt headers:{ Authorization:'JWT ' + sessionStorage.getItem('accessToken')}}).then(function(res){// 顯示結果 console.log(res.data);}).catch(function(err){console.log(err);});},requestError: function(xhr, errorType, error) {this.msg = xhr.responseText}}} </script>
?