day-044-forty-four-20230407-axios-fetch-pm2-url的组成
axios
axios是ajax封装的,基于Promise+XMLHttpRequest来进行的封装。
axios请求类型
- get类
-
种类
- axios.get()
- axios.head()
- axios.delete()
- axios.options()
-
语法
- axios.get(url[,config]) 返回一个Promise实例
- url 请求路径
- config 配置项 对象 可有可无
-
baseURL:基础路径
-
params:传递的参数
- 必须是一个无格式对象(plain object)或 URLSearchParams 对象
-
timeout: 超时时间
-
withCredentials: false 是否允许携带跨域资源凭证
-
responseType: ‘json’ //返回数据的类型
responseType
表示服务器响应的数据类型,- 可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’(默认), ‘text’, ‘stream’
-
onUploadProgress: function (progressEvent) {} 监控文件上传进度
-
onDownloadProgress: function (progressEvent) {} 监控文件下载进度
-
validateStatus 状态码成功范围
validateStatus: function (status) {//状态码成功范围 return status >= 200 && status < 300; // default }
-
- axios.get(url[,config]) 返回一个Promise实例
-
get的url全写
axios .get("http://localhost:8888/api/articleList?date=2021-05-21") .then((value) => { console.log(value); });
-
get的config分开写
axios .get("/api/articleList", { baseURL: "http://localhost:8888", params: { date: "2021-05-21", }, }) .then((response) => { return response.data; })
-
get配置参数
axios .get("/api/articleList", { baseURL: "http://localhost:8888", params: { date: "2021-05-21", }, timeout: 1000, withCredentials: false, responseType: "json", validateStatus: function (status) { return status >= 200 && status < 400; }, }) .then((response) => { return response.data; }) .then((value) => { console.log(value); }) .catch((err) => { console.log(err); });
-
get全写
axios({ method: "get", url: "/api/articleList", baseURL: "http://localhost:8888", params: { date: "2021-05-21", }, timeout: 1000, withCredentials: false, responseType: "json", validateStatus: function (status) { return status >= 200 && status < 400; }, }) .then((response) => { return response.data; }) .then((value) => { console.log(value); }) .catch((err) => { console.log(err); });
- axios(config) connfig 配置项—>对象
method:'get'
默认get,请求方式- url:请求的路径
- axios(config) connfig 配置项—>对象
-
- post类
-
种类
- axios.post()
- axios.put()
- axios.patch()
-
语法
- axios.post(url[,data,config])—返回一个Promise实例
- url:请求路径
- data:传递参数—>对象/字符串
- config:配置项, 可有可无
-
baseURL:基础路径
-
timeout: 超时时间
-
withCredentials: false 是否允许携带跨域资源凭证
-
responseType: ‘json’ //返回数据的类型
responseType
表示服务器响应的数据类型,- 可以是 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’(默认), ‘text’, ‘stream’
-
onUploadProgress 监控文件上传进度
onUploadProgress: function (progressEvent) {} 监控文件上传进度
-
onDownloadProgress 监控文件下载进度
onDownloadProgress: function (progressEvent) {} 监控文件下载进度
-
validateStatus 校验服务器返回状态码为多少才算请求成功
validateStatus: function (status) {//状态码成功范围 return status >= 200 && status < 300; // default }
-
transformRequest 允许在向服务器发送前,修改请求数据
- 当需要对传递的参数进行格式转化—需要对传递的参数二次处理时
- 只能用在 ‘PUT’, ‘POST’ 和 ‘PATCH’ 这几个请求方法****
- 一般处理后需要设置请求头为对应的格式,但当调用了transformRequest设置的方法后,axios会自动识别请求头的Content-Type
-
不过,如果担心axios识别不了请求头中请求体数据格式,也可以手动设置
//设置请求头信息 headers: {'Content-Type': 'application/x-www-form-urlencoded'}
-
-
- axios.post(url[,data,config])—返回一个Promise实例
-
post的配置
axios.post("/user/login",{ account:"18310612838", password:md5("1234567890")//md5方法是一个外部方法,需要引入,用于处理密码的转化。 },{ baseURL:"http://127.0.0.1:9999", transformRequest:function(data){//参数格式是 urlencoded //Qs.stringify() 将普通对象---》 urlencoded格式的数据 //console.log(Qs.stringify(data)); return Qs.stringify(data);//决定最终数据的格式//Qs.stringify()方法是外部Qs对象的一个内置方法,需要引入,用于把普通对象转成urlencoded格式的数据。 } }).then(response=>{ return response.data }).then(value=>{ console.log(value) }).catch(err=>{ console.log(err) })
-
post全写-axios.post()用axios()方式代替
-
method:“post”
-
url:“/user/login”
-
data:是作为请求主体被发送的数据
- 只适用于这些请求方法 ‘PUT’, ‘POST’, 和 ‘PATCH’
axios({ url:"/user/login", method:"post", data:{ account:"18310612838", password:md5("1234567890")//md5方法是一个外部方法,需要引入,用于处理密码的转化。 }, baseURL:"http://127.0.0.1:9999", transformRequest:function(data){//参数格式是 urlencoded return Qs.stringify(data);//决定最终数据的格式//Qs.stringify()方法是外部Qs对象的一个内置方法,需要引入,用于把普通对象转成urlencoded格式的数据。 } }).then(response=>{ return response.data }).then(value=>{ console.log(value) }).catch(err=>{ console.log(err) })
-
-
axios二次封装
Axios的二次配置 就是 将请求的公共部分提起出来
把多个请求之间公共的部分进行提取,后期在业务中再次发送数据请求,公共部分无需再次编写
-
原版的
<!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> </head> <body> <script src="axios.min.js">//这个是引入axios()的,用于发送axaj请求</script> <script src="md5.min.js">//这个是引入md5()方法的,用于加密密码</script> <script src="qs.js">//这个是引入Qs.stringify()方法的,用于把普通对象转成query格式字符串的</script> <script> axios.get("/api/articleList",{ baseURL:"http://localhost:8888", params:{ date:"2021-05-21" }, timeout:1000, withCredentials: false, validateStatus: function (status) { return status >= 200 && status < 400; } }).then(response=>{ return response.data; }).then(value=>{ console.log(value); }).catch(err=>{ console.log(err); }) axios.get("/api/swiper",{ baseURL:"http://localhost:8888", timeout:1000, withCredentials: false, validateStatus: function (status) { return status >= 200 && status < 400; } }).then(response=>{ return response.data; }).then(value=>{ console.log(value); }).catch(err=>{ console.log(err); }) axios.post("/user/login",{ account:"18310612838", password:md5("1234567890") },{ baseURL:"http://127.0.0.1:9999", transformRequest:function(data){ return Qs.stringify(data); } }).then(response=>{ return response.data }).then(value=>{ console.log(value) }).catch(err=>{ console.log(err) }) </script> </body> </html>
-
处理后的,axios做了公共的处理,在http.js中处理了一个。所以在html里,发起一个axios请求,不用做一些配置。
-
./http.js
//Axios 二次封装文件 //提取baseURL axios.defaults.baseURL = "http://localhost:8888"; //注释--》404错误 //axios.defaults.baseURL="http://localhost:8888"; //提出超时时间 axios.defaults.timeout = 1000; //请求超时错误 //axios.defaults.timeout=1; //提取 跨域资源凭证 axios.defaults.withCredentials = false; //提取状态码的范围设置 axios.defaults.validateStatus = function (status) { return status >= 200 && status < 400; }; //判断对象是不是纯对象 const isPlainObject = function isPlainObject(obj) { let proto, Ctor; if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false; proto = Object.getPrototypeOf(obj); if (!proto) return true; Ctor = proto.hasOwnProperty("constructor") && proto.constructor; return typeof Ctor === "function" && Ctor === Object; }; //post类提取 transformRequest axios.defaults.transformRequest = function (data) { //纯对象 {}---》urlencoded if (isPlainObject(data)) { data = Qs.stringify(data); //是纯对象才会转换 } return data; }; // 添加请求拦截器 //客户端----- 统一做某些操作 ----服务器 axios.interceptors.request.use( function (config) { // 在发送请求之前做些什么 // 发送请求的时候,一般会在请求头里统一配置 token // let token=... // if(token){ // config.headers.authorzation=token // } return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); } ); // 添加响应拦截器 //服务器----- 统一做某些操作 ----客户端 axios.interceptors.response.use( function (response) { // 对响应数据做点什么 //console.log(response,"111"); return response.data; }, function (error) { //错误 //1. 有状态码 // response--->status--->404/500 //2. 没有状态码的错误 // 2.1 请求超时 code: "ECONNABORTED" response: undefined // 2.2 断网 BOM对象--->navigator对象(浏览器相关信息)navigator.onLine true 有网 let err = "未知错误"; if (error.response) { //有状态码错误 switch (error.response.status) { case 404: err = "找不到页面"; break; case 500: err = "服务器错误"; break; //.... default: break; } } else { //没有状态码的错误 if (error.code === "ECONNABORTED") { err = "请求超时"; } else if (!navigator.onLine) { err = "没有网络"; } } // 对响应错误做点什么 return Promise.reject(err); } );
-
index.html
<!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> </head> <body> <script src="axios.min.js">//这个是引入axios()的,用于发送axaj请求</script> <script src="md5.min.js">//这个是引入md5()方法的,用于加密密码</script> <script src="qs.js">//这个是引入Qs.stringify()方法的,用于把普通对象转成query格式字符串的</script> <script src="http.js"></script> <script> axios.get("/api/articleList",{ params:{ date:"2021-05-21" } }).then(value=>{ console.log(value); }).catch(err=>{ console.log(err); }) axios.get("/api/swiper") .then(value=>{ console.log(value); }).catch(err=>{ console.log(err); }) axios.post("/user/login",{ account:"18310612838", password:md5("1234567890") },{ //自己配置的属性,优先级高于提取的部分 baseURL:"http://127.0.0.1:9999" }).then(value=>{ console.log(value) }).catch(err=>{ console.log(err) }) </script> </body> </html>
-
设置axios默认配置
-
axios.defaults.xxx 默认配置
-
统一配置默认配置-baseURL
- axios.defaults.baseURL = “http://localhost:8888”;
-
统一配置默认配置-超时时间
- axios.defaults.timeout = 1000;
-
统一配置默认配置-跨域资源凭证
- axios.defaults.withCredentials = false;
-
统一配置默认配置-状态码的范围设置
axios.defaults.validateStatus = function (status) { return status >= 200 && status < 400; };
-
统一配置默认配置-transformRequest
-
post类统一生效,虽然get类也相当于设置了,但get类请求并不会使用这里
//判断对象是不是纯对象 const isPlainObject = function isPlainObject(obj) { let proto, Ctor; if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false; proto = Object.getPrototypeOf(obj); if (!proto) return true; Ctor = proto.hasOwnProperty("constructor") && proto.constructor; return typeof Ctor === "function" && Ctor === Object; }; axios.defaults.transformRequest = function (data) { //纯对象 {}---》urlencoded if (isPlainObject(data)) { data = Qs.stringify(data); //是纯对象才会转换//Qs.stringify()方法是外部Qs对象的一个内置方法,需要引入,用于把普通对象转成urlencoded格式的数据。 } return data; };
-
-
设置axios数据拦截器
- 请求拦截器:发生在 “配置项准备完毕” 和 “发送请求” 之间
- 添加请求拦截器
- 客户端----- 统一做某些操作 ----服务器
-
这里统一做某些操作的时机就在请求拦截器里进行
axios.interceptors.request.use( function (config) { // 在发送请求之前做些什么 // 发送请求的时候,一般会在请求头里统一配置 token // let token=... // if(token){ // config.headers.authorzation=token // } return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); } );
- config对象包含的就是准备好的配置项,最后返回啥配置,就按照这些配置发请求。这个操作在第一个函数中执行。返回的结果就是ajax发送的请求头及请求体。
- config对象也可能错误,比如url设置错了之类的。处理错误但也要返回错误,因为后续别人可能要用catch来接收及处理。
- 返回的结果就是axios返回的Promise实例对象的catch()中得到的值。
-
- 客户端----- 统一做某些操作 ----服务器
- 添加请求拦截器
- 响应拦截器:发生在 “服务器返回结果” 和 “业务代码自己处理 .then” 之间
- 添加响应拦截器
-
服务器----- 统一做某些操作 ----客户端
axios.interceptors.response.use( function (response) { // 对响应数据成功的返回值做点什么 //console.log(response,"111"); return response.data; }, function (error) { //错误 //1. 有状态码 // response--->status--->404/500 //2. 没有状态码的错误 // 2.1 请求超时 code: "ECONNABORTED" response: undefined // 2.2 断网 BOM对象--->navigator对象(浏览器相关信息)navigator.onLine true 有网 let err = "未知错误"; if (error.response) { //有状态码错误 switch (error.response.status) { case 404: err = "找不到页面"; break; case 500: err = "服务器错误"; break; //.... default: break; } } else { //没有状态码的错误 if (error.code === "ECONNABORTED") { err = "请求超时"; } else if (!navigator.onLine) { err = "没有网络"; } } // 对响应错误做点什么 return Promise.reject(err); } );
- 第一个函数形参一般为后端成功返回消息后才执行,返回的结果就是axios返回的Promise实例对象的then()第一个函数中的结果。
- 第二个函数开始一般为后端没有成功返回后才执行。
- 返回的结果就是axios返回的Promise实例对象的catch()中得到的值。
- 错误分两类
- 有状态码
- 如: response—>status—>404/500
- 没有状态码的错误
- 请求超时 code: “ECONNABORTED” response: undefined
- 断网
- 可以用 BOM对象—>navigator对象(浏览器相关信息)来判断
- navigator.onLine true 有网
- 可以用 BOM对象—>navigator对象(浏览器相关信息)来判断
- 有状态码
-
- 添加响应拦截器
fetch
fetch是es6 新增的,其核心并不是XMLHttpRequest。而是一个与XMLHttpRequest平级的基础通信功能。
fetch语法
- fetch(url,config) 返回一个Promise实例对象
- url:请求路径 get类参数直接拼接到url的后面
- config 配置项
-
method: ‘POST’, // *GET(默认get), POST, PUT, DELETE
-
mode: ‘cors’,是否允许跨域
- no-cors(不允许), *cors(允许), same-origin(同源允许)
-
credentials:是否是否允许携带跨域资源凭证
- include(允许), *same-origin(同源允许), omit(不允许)
-
cache: ‘no-cache’;是否缓存 不缓存no-cache
-
headers 设置请求头
headers: { 'Content-Type': 'application/x-www-form-urlencoded', },
-
body: JSON.stringify(data) post类请求的参数
let data={ account:"18310612838", password:md5("1234567890") } fetch("http://127.0.0.1:9999/user/login",{ method:"POST", mode: 'cors', credentials:"omit", headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body:Qs.stringify(data) }).then(response=>{ return response.json()//接收数据,数据格式是json }).then(value=>{ console.log(value); })
-
Promise实例对象的正确结果返回值
fetch()返回的Promise实例对象的正确结果的结果值不是一个对象,而是一个Response实例对象。
fetch("./",{
mode: 'cors',
credentials:"omit"
}).then(response=>{
console.log(response)//不会存在数据,必须调用原型上的方法才能获取数据
//原型上的方法,只能执行1次,多了就报错
return response.json()//接收数据,数据格式是json
}).then(value=>{
console.log(value);
})
- Response实例对象不会存在数据,必须调用Response原型上的方法才能获取数据
- response.text():得到文本字符串。
- response.json():得到 JSON 对象。
- response.blob():得到二进制 Blob 对象。
- response.formData():得到 FormData 表单对象。
- response.arrayBuffer():得到二进制 ArrayBuffer 对象。
- 同一个Response实例对象,它的原型上的方法,只能执行1次,多了就报错
pm2
一般打开一个前端的后台项目,需要用node执行,同时该cmd窗口不能关闭,监听的端口才会起作用
而pm2可以替代node执行一些命令
在pm2关闭窗口后,对应的后台服务仍然开启 除非关闭电脑,或者适用特定的命令关闭
安装pm2
npm i pm2 -g
pm2命令
-
pm2 list 查看启动的服务
-
查看全局启动的pm2项目
pm2 list //查看启动的项目
-
-
pm2 start xxx.js --name XXX 启动项目
-
pm2 stop XXX(名称) 关闭XXX服务
-
pm2 restart XXX 重新启动项目
-
pm2 delete XXX 删除某个服务
-
pm2 start all启动所有项目
-
pm2 log 查看日志
url的组成
-
例子
let theUrl1 = `http://127.0.0.1:8848/aaa2023_01/aaa.html?name=lili&age=18#teacher` let theUrl2 = `http://www.baidu.com/aaa2023_01/aaa.html?name=lili&age=18#teacher`