1. Addressing cross-domain issues
1. In the index.js file under the config folder of Vue2.0 or in vue3.0, create a vue.config.js file and write the following code:
module.exports = {
devServer: {
open: true.port: 8080.// The above IP and port are our own; The following are those that need to cross domains
proxy: { // Configure cross-domain
'/apis': {
target: 'http://47.98.143.163:8000/'.// Here is the background address simulation; Should fill in your real background interface
ws: true.changOrigin: true.// Allow cross-domain
pathRewrite: {
'^/apis': ' ' // Use this API when requesting}}}},}Copy the code
- Pass in the method that calls the interface
/apis
Add an interface to fetch data as shown in the following example:
// Edit the list of questionnaires
edit(id) {
this.axios
.put("/apis/zhmq/wj/wj/" + id + "/", {
title: this.inputtitle,
explain: this.titletextarea,
})
.then((res) = > {
console.log(121324654);
this.centerDialogVisible = false;
this.getarr();
})
.catch((e) = > fn);
}
Copy the code
2. Login to obtain the token
When retrieving the backend interface, I need to pass a token to the backend to get the data of the backend, but the backend does not give me the login interface, let me use another project login token, the result is that suddenly there is no data… , the code was like this:
return: {token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwic2Vzc2lvbl9pZCI6Ijg0MmRlNGQ0LTVkODktND g0ZC1hMDk1LWMzNTdkNmJmNDRjMSIsImV4cCI6MTYyOTQyNTI4Mywib3JpZ19pYXQiOjE2MjkzMzg4ODN9.AeO5kKdojnF3kjnIfmuShMyEvOvVLavkc4gcU nH9giU"
}
getlist(){
this.axios
.get("/apis/zhmq/wj/wj/display/" + this.titleId + "/", {
// Add the request header
headers: {
Authorization: "Bearer " + this.token,
},
})
.then((res) = > {
console.log(res);
})
.catch((e) = > fn);
}
Copy the code
I need to copy and paste headers every time I switch to an interface, and the token will soon expire. I am really upset, so I have to discuss with the backend to ask him to give me a login interface, otherwise it is really troublesome.
3. Develop a login page to store tokens
- Write the login page first and fetch it at the same time
token
,token
Stored in thevuex
, the code is as follows:
<template>
<div class="login">
<el-form
:model="loginForm"
:rules="fieldRules"
ref="loginForm"
label-position="left"
label-width="0px"
class="demo-ruleForm login-container"
>
<h2 class="title" style="padding-left: 22px">System login</h2>
<el-form-item prop="account">
<el-input
type="text"
v-model="loginForm.account"
auto-complete="off"
placeholder="Account"
></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
type="password"
v-model="loginForm.password"
auto-complete="off"
placeholder="Password"
></el-input>
</el-form-item>
<el-form-item class="join_formitem">
<el-form-item class="captcha">
<el-col :span="12">
<el-form-item prop="picLyanzhengma">
<el-input
type="text"
placeholder="Please enter the verification code."
class="yanzhengma_input"
v-model="loginForm.picLyanzhengma"
/>
</el-form-item>
</el-col>
<el-col class="line" :span="1"> </el-col>
<el-col :span="11">
<input
type="button"
@click="createdCode"
class="verification"
v-model="checkCode"
/>
</el-col>
</el-form-item>
</el-form-item>
<el-form-item>
</el-form-item>
<el-form-item style="width: 100%">
<! -- <el-button type="primary" style="width:48%;" @click.native. Prevent ="reset"> </el-button> -->
<el-button type="primary" style="width: 48%" @click="login()"
>Log in < / el - button ></el-form-item>
</el-form>
</div>
</template>
<script>
import { mapMutations } from "vuex";
import Cookies from "js-cookie";
export default {
name: "login".components: {},data() {
return {
code: "".checkCode: "IHLE".data: "".loading: false.loginForm: {
account: "admin".password: "123456".captcha: "".src: "".picLyanzhengma: "",},fieldRules: {
account: [{ required: true.message: "Please enter your account number".trigger: "blur"}].password: [{ required: true.message: "Please enter your password".trigger: "blur"}].picLyanzhengma: [{required: true.message: "Please enter the verification code.".trigger: "blur"},],},checked: false}; },methods: {
...mapMutations(["changeLogin"]),
login() {
this.loading = true;
let _this = this;
this.axios
.post("/apis/admin/login/", { // Retrieve the back-end login interface
username: this.loginForm.account,
password: this.loginForm.password,
})
.then((res) = > {
console.log(res);
console.log(res.data.data.token);
_this.userToken = "Bearer " + res.data.data.token;
// Save the user token to vuex
_this.changeLogin({ Authorization: _this.userToken });
Cookies.set("Token", res.data.data.token); // Store the token in a cookie after successful login
_this.$router.push("/questionnaire");
});
},
reset() {
this.$refs.loginForm.resetFields();
},
// Random verification code
createdCode() {
// Empty the verification code input first
this.code = "";
this.checkCode = "";
this.picLyanzhengma = "";
// Verification code length
const codeLength = 4;
/ / random number
const random = new Array(
0.1.2.3.4.5.6.7.8.9."A"."B"."C"."D"."E"."F"."G"."H"."I"."J"."K"."L"."M"."N"."O"."P"."Q"."R"."S"."T"."U"."V"."W"."X"."Y"."Z");
for (let i = 0; i < codeLength; i++) {
// Get index of random number (0~35)
let index = Math.floor(Math.random() * 36);
// add a random number to code according to the index
this.code += random[index];
}
// Assign the code value to the captcha
this.checkCode = this.code; }},mounted() {
this.createdCode(), // Create a verification code}};</script>
<style lang="scss" scoped>
.login {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
// height: 600px;
background-image: url(".. /.. /assets/login-background.jpg");
background-size: cover;
}
.login-container {
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-border-radius: 5px;
background-clip: padding-box;
margin: 100px auto;
width: 350px;
padding: 35px 35px 15px 35px;
background: #fff;
border: 1px solid #eaeaea;
box-shadow: 0 0 25px #cac6c6;
.title {
margin: 0px auto 30px auto;
text-align: center;
color: # 505458;
}
.remember {
margin: 0px 0px 35px 0px; }}.yanzhengma_input {
font-family: "Exo 2", sans-serif;
// border: 1px solid #fff;
// color: #fff;
outline: none;
// border-radius: 12px;
letter-spacing: 1px;
font-size: 17px;
font-weight: normal;
// background-color: rgba(82.56.76.15);
padding: 5px 0 5px 10px;
// margin-left: 30px;
height: 30px;
margin-top: 30px;
// border: 1px solid #e6e6e6;
}
.verification {
background: white;
margin-top: 35px;
border-radius: 12px;
width: 100px;
letter-spacing: 5px;
margin-left: 50px;
height: 40px;
transform: translate(-15px.0);
}
.captcha {
height: 50px;
text-align: justify;
}
</style>
Copy the code
The back-end login interface is successfully accessed and the token is obtained and stored in the VUEX
- in
store
Under the folderindex.js
File, write the following code, willtoken
Stored in thelocalStorage
In:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
/ / store token
Authorization: localStorage.getItem('Authorization')?localStorage.getItem('Authorization') : ' '
},
mutations: {
// Modify the token and store the token to localStorage
changeLogin(state, user) {
state.Authorization = user.Authorization;
localStorage.setItem('Authorization', user.Authorization); }}});export default store;
Copy the code
3. Write the following code to the main.js file:
/ / introduce axios
import axios from 'axios'
/ / use axios
Vue.prototype.axios = axios
/ / axios carry a token
// Add request interceptor, add token to request header
axios.interceptors.request.use(
config= > {
if (localStorage.getItem('Authorization')) {
config.headers.Authorization = localStorage.getItem('Authorization');
}
return config;
},
error= > {
return Promise.reject(error);
});
Copy the code
When the interface is requested, the token can be carried to get the back-end data, so the addition of the request header can be omitted by calling the back-end interface:
// Edit the list of questionnaires
edit(id) {
this.axios
.put("/apis/zhmq/wj/wj/" + id + "/", {
title: this.inputtitle,
explain: this.titletextarea,
})
.then((res) = > {
console.log(121324654);
this.centerDialogVisible = false;
this.getarr();
})
.catch((e) = > fn);
}
Copy the code
4. Interception of routes through tokens
Add the following code to the index.js file in the main.js router folder to perform the global route guard:
router.beforeEach((to, from, next) = > {
if (to.path == '/login' || to.path == '/register') {
next();
} else {
const token = localStorage.getItem('Authorization'); / / access token
// Token does not exist
if (token === null || token === ' ') {
alert('You are not logged in yet, please log in first');
next('/login');
} else{ next(); }}});Copy the code
Complete login route interception and request carrying request headers