json-server的介绍与服务搭建
作用
快速创建一个接口,以供Ajax请求
安装及使用
第三步(注意路径以及在运行代码前加上npx)
axios的介绍与页面配置
在项目中
1.$ npm install axios
2.$ yarn add axios
学习阶段使用CDN方式
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
在Bootcdn里面搜索axios,查找出来的网址可以替换上面的网址
axios基本使用
Axios是一个基于Promise的http客户端,运行在浏览器/NodeJS上,向远程发送Ajax/http请求, 支持请求响应拦截器,支持请求响应的数据解析,支持取消请求,支持JSON处理,支持扩展攻击的防护
- 可以使用npm安装在Node上(或在项目打包的时候)
- 可以使用script标签引入
Axios被引入后与jQuery类似,只有一个axios函数
尝试实现Get/Post/Put/Delete请求
实现点击不同请求方式的按钮,发送不同请求到JSON-Server
<div class="container"><h2 class="page-header">基本使用</h2><button class="btn btn-primary">发送GET请求</button><button class="btn btn-warning">发送post请求</button><button class="btn btn-success">发送put请求</button><button class="btn btn-danger">发送 delete 请求</button></div><script>// 获取按钮const btns = document.querySelectorAll('button')btns[0].onclick = function() {// 发送 ajax请求axios({// 请求类型method: 'GET',// urlurl: 'http://localhost:3000/posts/2',}).then(response => {console.log(response);})}// 添加一篇新的文章btns[1].onclick = function() {// 发送 ajax请求axios({// 请求类型method: 'POST',// urlurl: 'http://localhost:3000/posts',// 请求体data: {title: "今晚月色正好",author: "z"}}).then(response => {console.log(response);})}// 更新数据btns[2].onclick = function() {// 发送 ajax请求axios({// 请求类型method: 'PUT',// urlurl: 'http://localhost:3000/posts/3',// 请求体data: {title: "今晚月色正好",author: "z"}}).then(response => {console.log(response);})}// 删除数据btns[3].onclick = function() {// 发送 ajax请求axios({// 请求类型method: 'DELETE',// urlurl: 'http://localhost:3000/posts/3',// 请求体 删除数据无需设置请求体// data: {// title: "晚上涛哥没回消息",// author: "vera"// }}).then(response => {console.log(response);})}
axios其他方式发送请求
axios.request
axios.head
axios.option
axios.patch
axios响应数据结构
{"data": {...}, // 响应体对象"status": 201, // 响应状态码"statusText": "Created", // 响应内容"headers": { // 响应头"cache-control": "no-cache","content-length": "48","content-type": "application/json; charset=utf-8","expires": "-1","location": "http://127.0.0.1:3000/posts/9","pragma": "no-cache"},"config": { // 请求配置"url": "http://127.0.0.1:3000/posts","method": "post"// ...},"request": {} // 原生的Ajax对象
}
axios请求对象数据结构
{// 访问的URL,如果设置了baseurl(后面会有),可以直接写后半部分url: 'http://127.0.0.1:3000/posts',// url: '/posts',// 请求方式method: 'get', // default// baseurl是url最基础的部分,如果这里有填数据,那么请求的时候会把url替换成baseurl+url 除非url被写为绝对路径baseURL: 'https://127.0.0.1:3000',// 在发送请求之前对数据进行处理的函数// 仅支持 'PUT', 'POST', 'PATCH' and 'DELETE'// 这是一个函数列表,最后一个函数必须返回字符串/JS的Buffer/JS的Buffer数组transformRequest: [function (data, headers) {// ...return data;}],// 对响应结果进行处理transformResponse: [function (data) {// ...return data;}],// 配置请求头信息headers: {'X-Requested-With': 'XMLHttpRequest'},// 设置url参数,例如Get的时候向下面这么写,就转化为?ID=12345params: {ID: 12345},// 参数序列化(格式化)函数paramsSerializer: function (params) {return Qs.stringify(params, {arrayFormat: 'brackets'})},// 请求体设置: 支持对象或者字符串,Axios最后都会转换成字符串,仅支持 'PUT', 'POST', 'DELETE , and 'PATCH'data: {firstName: 'Fred'}, // data: 'Country=Brasil&City=Belo Horizonte',// 设置超时时间, 超时后自动取消, 单位mstimeout: 1000,// 跨域请求时候设置是否携带cookiewithCredentials: false, // default// 设置请求适配器adapter: function (config) {/* ... */},// http的基础认证(有的页面要输入访问的用户名密码)auth: {username: 'janedoe',password: 's00pers3cret'},// 设置响应体格式responseType: 'json', // default// 字符集设置responseEncoding: 'utf8', // default// 跨域请求时cookie名设置 防止跨站攻击xsrfCookieName: 'XSRF-TOKEN', // default// 跨域请求头设置xsrfHeaderName: 'X-XSRF-TOKEN', // default// 上传时回调函数onUploadProgress: function (progressEvent) {// ...},// 下载时回调函数onDownloadProgress: function (progressEvent) {// ...},// 响应的最大长度maxContentLength: 2000,// 响应体最大长度maxBodyLength: 2000,// 如何定义响应成功validateStatus: function (status) {return status >= 200 && status < 300; // default},
bu kanrects: 5, // default// 设置socket文件位置socketPath: null, // default// 请求设置httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),// 代理设置,一般用于Node爬虫proxy: {protocol: 'https',host: '127.0.0.1',port: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},// 请求取消函数cancelToken: new CancelToken(function (cancel) {}),bu kan否解压结果(仅用于Node)decompress: true // default// 可能会在较新版本中删除的向后兼容性过渡选项transitional: {silentJSONParsing: true; // default value for the current Axios versionforcedJSONParsing: true;clarifyTimeoutError: false;}
}
axios默认配置
可以设置config的默认值
直接设置axios.default.config参数 = "XX"
,
例如axios.default.method = "GET"(设置默认的请求类型为GET)
axios.default.baseURL='http://localhost:3000';(设置基础URL)
创建实例对象发送ajax请求
const duanzi = axios.create({baseURL:'https://api.apiopen.top/getSingleJoke',timeout:3000,method:"get"
}) duanzi({params:{sid:28654780}
}).then(d=>{console.log(d.data)})
使用了axios.creat()函数创建了一个duanzi对象用来获取段子,并且添加了一些参数,这个段子对象是一个函数,这个函数与Axios()的功能是一样的,相当于就是一个设置了默认参数作用域的Axios。
我们可以调用函数发送Axios请求,这里参数列表设置sid是测试API文档要求的,我们还可以仿照axios.get()使用duanzi.get()
axios拦截器
- 拦截器就是一个函数,有两类拦截器,请求拦截器和响应拦截器
- 拦截器与中间件较为相似,就是在发送请求之前与收到响应之后对config/data进行判断,并抛出resolve/reject
- 当拦截器抛出结构后,Axios会执行promise链上的对应步骤(继续发送请求还是取消请求等等可以暂时不管)
- 拦截器与transformRequest/transformResponse有一定的区别,拦截器的返回结果是一个Promise对象,出错可以直接执行Promise链上的对应函数,但是transformRequest/transformResponse是一个函数列表,返回值是发送/收到的数据,前者是用于判定请求是否合法决定要不要继续运行的,后者是在合法基础上对数据进行处理的,有一定的区别。
一个简单使用
axios.interceptors.request.use(function(config){// 参数就是我们Axios请求中的config,我们可以对他进行判断,修改console.log("请求拦截器 成功");// 这里要返回一个对象用于设置请求return config;
},function(error){console.log("请求拦截器 失败");// 返回一个Promise的refuse对象return Promise.reject(error)
});axios.interceptors.response.use(function(response){// 参数是Axios的默认请求结果console.log("响应拦截器 成功");// 在这里不是必须返回发来的reponse,可以是任意的return response;
},function(error){console.log("响应拦截器 失败");return Promise.reject(error)
});axios.request({method : "GET",url : "http://127.0.0.1:3000/posts"
}).then(d=>{console.log(d.data)
})
返回结果
请求拦截器 成功
响应拦截器 成功
// 获得的数据
运行的顺序是请求拦截器运行,返回config(配置对象),发收请求,响应拦截器运行,返回结果,打印。
拦截器基本结构
请求拦截器
axios.interceptors.request.use(function(config){// 成功的处理return config;
},function(error){// 失败的处理return Promise.reject(error)
});
参数:
请求拦截器有两个回调函数
- 如果成功,那么执行第一个回调函数,这个回调函数的参数是上一个Promise发来的config
- 如果失败,那么执行第二个回调函数,这个回调函数的参数是错误的reject
- 如果某个回调函数判定当前数据有误,返回Promise.reject
- 如果某个回调函数判定当前数据正确,返回Promise.resolve (直接return config,必须有config用于下一个函数调用)
响应拦截器
axios.interceptors.response.use(function(response){// 成功的处理return response;
},function(error){// 失败的处理return Promise.reject(error)
});
参数:
响应拦截器有两个回调函数
- 如果成功,那么执行第一个回调函数,这个回调函数的参数是上一个Promise发来的自定义对象,这个对象会作为响应的结果返回
- 如果失败,那么执行第二个回调函数,这个回调函数的参数是错误的reject
- 如果某个回调函数判定当前数据有误,返回Promise.reject
- 如果某个回调函数判定当前数据正确,返回Promise.resolve (直接return 想返回的数据,可以与response有很大区别)
如果代码中存在多个请求拦截器或者响应拦截器,那么会代码中出现的次序逆序执行请求拦截器/顺序执行响应拦截器。
取消请求
let cancelFlag = null; // 请求取消函数
// 请求按钮
btn_req.onclick=(e)=>{axios({method : "GET",url : "http://127.0.0.1:3000/posts",// 多加入一行,cancelTocken是一个回调函数,对象是axios的新取消,设置请求取消函数cancelToken: new axios.CancelToken((c)=>{cancelFlag = c;})}).then(()=>{console.log("OK")})
};// 取消请求按钮
btn_can.onclick=(e)=>{cancelFlag();console.log("Cancel")
};
设置json-server响应延迟2000ms
json-server --watch db.json --delay 2000