###01 - feedback
02 review
-
Scientific Internet access
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-bSNxHjGn-1631678760356)(docs/media/1566714959699.png)]
-
When you need to get dom elements, get instances of other groups.
- ref vue provides the value of the attribute
- r e f s of yes as genus to When front v u e real example ' t h i s . The object of refs belongs to the current vue instance ` this The object of refs belongs to the value of the 'this.refs. Attribute of the current vue instance`
-
review
- Check function
- Custom verification
- Overall verification
- Simple login
- Perfect login
- The home page is basically completed
###03 login supplement review session
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-k9s3iWy2-1631678760358)(docs/media/1566716520662.png)]
- Summary: cookie s under different domain names cannot be shared.
###04 - login supplement - know token
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-o1hfplua-163167876360) (docs / media / 1566717326147. PNG)]
- After successful login: the user information is saved in the client.
- Every request: a token needs to be appended to the request header
05 login supplement postman tool
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG ugliojvt-1631678760363) (docs / media / 1566718037401. PNG)]
- Conclusion: add token to the head
- Field name: Authorization
- Field value: Bearer + space + token
###06 - login supplement - review local storage
sessionStorage usage:
- setItem(key,value) value requirements: it must be a string, and json is used to store complex data.
- getItem(key) returns null if there is no data
- removeItem(key)
- clear()
- Supplement: sessionStorage takes effect under the current domain name.
07 - login supplement - save user information
Define a module to operate local user information, store/index.js
// Responsible for: storage, acquisition and deletion of user information const KEY = 'hm-toutiao-80-user' export default { setUser (user) { // Store user information // user data type object const jsonStr = JSON.stringify(user) window.sessionStorage.setItem(KEY, jsonStr) }, getUser () { // Get user information const jsonStr = window.sessionStorage.getItem(KEY) || '{}' // There may be no null data returned. An error is reported through null.token, but the {}. Token value is undefined return JSON.parse(jsonStr) }, delUser () { // Delete user information window.sessionStorage.removeItem(KEY) } }
Save user information when login is successful: views/login/index.vue
+ import store from '@/store' //.... .then(res => { // Successful jump // Note that the login is not perfect // Res is the response object -- > res.data response body -- > res.data.data response body contains (message,data) // User information res.data.data // Operating user information is to operate the store to store and write a module to operate user information. + store.setUser(res.data.data) this.$router.push('/') })
08 - login supplement - access control
-
Except for the login page, other pages can only be accessed after successful login.
- Judge whether the login is successful according to whether there is user information in the local storage.
- Before jumping the route, judge the login status:
- Login, release.
- Not logged in, blocked, go to the login page.
-
Use the advanced routing function: navigation guard.
const router = new VueRouter({ ... }) // Front guard router.beforeEach((to, from, next) => { // to where // from where // next() releases next('/login') and intercepts login })
Implementation code: router/index.js
// Front guard router.beforeEach((to, from, next) => { // //1. The path is released when logging in // if (to.path === '/login') return next() // //2. It is not the time to log in and there is no log in to intercept the login page // if (!store.getUser().token) return next('/login') // //3. Release under other circumstances // next() if (to.path !== '/login' && !store.getUser().token) return next('/login') next() })
09 Axios default configuration options
-
Add additional configuration when requested. https://www.kancloud.cn/yunye/axios/234845
-
baseURL function: reference path
axios.defaults.baseURL = 'http://ttapi.research.itcast.cn/mp/v1_0/'
-
Headers: Customize request headers
axios.defaults.headers.Authorization = Bearer + Space + token
-
-
In api/index.js
// Configure an axios export that meets the needs of the project for global configuration import axios from 'axios' import store from '@/store' // Configure // 1. Reference address axios.defaults.baseURL = 'http://ttapi.research.itcast.cn/mp/v1_0/' // 2. Request header token axios.defaults.headers.Authorization = `Bearer ${store.getUser().token}` export default axios
- Use main.js
// Simply configure axios -import axios from 'axios' +import axios from '@/api' Vue.prototype.$http = axios
10 Axios request interceptor
-
Phenomenon:
- When you log in, there is no token stored
- After clicking login, you will jump to the home page (token s have been stored), without refreshing the whole page and updating some parts.
- After you come to the home page, you send a request without a token
- After refreshing the page, send a request with a token
-
explain
- Main.js imports all the code. After loading the page, the code of main.js will be executed once.
- api/index.js is executed once
- axios.defaults.headers.Authorization = Bearer ${store.getUser().token}
- Authorization : Bearer undefined
- After the home page is refreshed, the code of main.js is executed again.
- Main.js imports all the code. After loading the page, the code of main.js will be executed once.
-
Scheme:
- Before each request, get the token and set it to the header.
// Add request interceptor // The function in use is called before each request // The first function: intercepting the request is called successfully // The second function: the execution of the second function is triggered only when an error is reported when intercepting a request and doing business. axios.interceptors.request.use(function (config) { // Parameter config request configuration default configuration // Modify the configuration and add token information // Use your modified configuration when returning the modified configuration request return config; }, function (error) { // Error error object // What to do about request errors // Returns a promise object that must be in error // New promise ((resolve, reject) = > {}) may succeed or fail // Promise.reject(error) must be a catch() call failure // Promise.resolve() must be successful in calling then() return Promise.reject(error); });
Specific implementation:
// Request interceptor (before each request) axios.interceptors.request.use(config => { // Modify configuration and add token config.headers.Authorization = `Bearer ${store.getUser().token}` return config }, (err) => { return Promise.reject(err) })
11 Axios response interceptor
- The front end stores the token
- The back-end stores the token, but it is valid for 2 hours.
- The background will return information and respond to the status code 401. In each response, judge the status code. If 401 intercepts and jumps to login
// Add a response interceptor (each time the backend gives you a response) axios.interceptors.response.use(function (response) { // Response successful // Do something about the response data return response; }, function (error) { // Response failed // 401 error acquisition response status code to judge whether it is 401 // error.response response response object // error.response.status status status code // Do something about response errors return Promise.reject(error); });
Specific implementation:
import router from '@/router' // Response interceptor (after each response) // res => { return res } ==== res => res axios.interceptors.response.use(res => res, err => { // Own logic // 1. Get status code const status = err.response.status // 2. Judgment 401 if (status === 401) { // 3. Clear invalid token s store.delUser() // 4. Jump login // 4.1 the path router in native mode is implemented based on hash / login = = > # / login // window.location.hash = '#/login' // 4.2 use router to jump to $router main.js, import the instance of router/index.js, and mount it under the vue root instance. router.push('/login') } return Promise.reject(err) })
carding:
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-djrj9cfw-163167876364) (docs / media / 156672777068. PNG)]
Use of 12 Axios async with await
- axios is based on promise encapsulation.
- promise function: solve the asynchronous writing of callback hell and make the asynchronous logic clearer.
- ES6 provides the keyword async await, which uses synchronous writing to perform asynchronous operations. The logic is clear and elegant.
Required scenarios:
- When you request interface A, you can obtain the data of interface B.
export default { async created () { // 1. calling the A interface with promise, calling the B interface to get all the data. // this.$http.get('http://localhost:3000/a') // .then(res => { // console.log(res.data) // A // return this.$http.get('http://localhost:3000/b') // }) // .then(res => { // console.log(res.data) // B // }) // 2. use async await to call A interface and call B interface to get all data. // If the function decorated with await (return value promise) is used, then: the result after the return value is successful // await executes this function synchronously, which hinders the execution of the current program // The use of await must be inside the function decorated with async (the outer function of await must be added with async) const resA = await this.$http.get('http://localhost:3000/a') const resB = await this.$http.get('http://localhost:3000/b') console.log(resA.data, resB.data) } }
###13 Axios modify login asynchronous operation