1.请求过程概述
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> </head> <body> <script> // 设置请求拦截器 axios.interceptors.request.use(function(config) { console.log("请求拦截器成功"); return config; }, function(error) { console.log("请求拦截器失败"); return Promise.reject(error); }); // 设置响应拦截器 axios.interceptors.response.use(function(response) { console.log("响应拦截器成功"); return response; }, function(error) { console.log("响应拦截器失败"); return Promise.reject(error); }); axios({ method: "GET", url: "http://localhost:3000/posts", }).then(response => { console.log(response); console.log("请求过程成功!!!"); }) </script> </body> </html>
效果展示:
2.请求顺序解析
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> </head> <body> <script> // 设置请求拦截器 axios.interceptors.request.use(function(config) { console.log("请求拦截器成功 1号"); // throw "参数出了问题"; return config; }, function(error) { console.log("请求拦截器失败 1号"); return Promise.reject(error); }); axios.interceptors.request.use(function(config) { console.log("请求拦截器成功 2号"); // throw "参数出了问题"; return config; }, function(error) { console.log("请求拦截器失败 2号"); return Promise.reject(error); }); // 设置响应拦截器 axios.interceptors.response.use(function(response) { console.log("响应拦截器成功 1号"); return response; }, function(error) { console.log("响应拦截器失败 1号"); return Promise.reject(error); }); axios.interceptors.response.use(function(response) { console.log("响应拦截器成功 2号"); return response; }, function(error) { console.log("响应拦截器失败 2号"); return Promise.reject(error); }); axios({ method: "GET", url: "http://localhost:3000/posts", }).then(response => { console.log(response); console.log("请求过程成功!!!"); }) </script> </body> </html>