赞
踩
https://github.com/typicode/json-server
json-server的作用
1.快速搭建一个http服务,可以在30秒内不需要任何编码创建一个假的服务器
2.axios需要向服务端发送请求,需要服务端结合axios
创建服务过程:
1.install
2.创建db.json
install
npm install json-server
run
npx json-server db.json
或
json-server --watch db.json
延迟响应
json-server --watch db.json -d 2000
https://github.com/axios/axios
定义:
特点:连接请求和响应;对请求和相应数据做转化;取消请求;自动转化为json数据;保护阻挡XSRF攻击
配置:
1.使用npm
$ npm install axios
2.使用brower
$ bower install axios
3.使用yarn
和npm是一个意思
$ yarn add axios
4.使用CDN
在网页中进行引入
CDN 国内CDN网站: https://www.bootcdn.cn/
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
基本使用-使用axios这个函数发送请求
1.GET
btns[0].onclick = function(){
//发送 AJAX 请求(axios返回Promise对象,所以用then方法指明成功的回调)
axios({
//请求类型
method: 'GET',
//URL
url: 'http://localhost:3000/posts/2',
}).then(response => {
// 获取结果
console.log(response);
});
}
2.POST
添加新内容 请求体将内容传给服务器 json-server对内容保存
//4-添加一篇新的文章 发送post请求
btns[1].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'POST',
//URL
url: 'http://localhost:3000/posts',
//设置请求体
data: {
id: "3",
title: "今天天气不错, 还挺风和日丽的",
author: "张三"
}
}).then(response => {
console.log(response);
});
}
3.PUT
//更新数据 将id为3的文章更改内容
btns[2].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'PUT',
//URL
url: 'http://localhost:3000/posts/3',
//设置请求体
data: {
title: "今天天气不错, 还挺风和日丽的",
author: "李四"
}
}).then(response => {
console.log(response);
});
}
4.delete
//删除数据
btns[3].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'delete',
//URL
url: 'http://localhost:3000/posts/3',
}).then(response => {
console.log(response);
});
}
其他使用:使用axios对象当中的一些方法来发送请求
//发送 GET 请求
btns[0].onclick = function(){
// axios()
axios.request({
method:'GET',
url: 'http://localhost:3000/comments'
}).then(response => {
console.log(response);
})
}
//发送 POST 请求
btns[1].onclick = function(){
// axios()
axios.post(
'http://localhost:3000/comments',
{
"body": "喜大普奔",
"postId": 2
}).then(response => {
console.log(response);
})
}
Console
config 配置对象,包含请求类型、url、请求体
data 响应体的结果(服务器的响应结果)
headers 响应头信息
request 原生AJAX请求
axios(config)
配置项就是axios函数的参数
{
// `url` 是用于请求的服务器 URL,设置给谁发送请求
url: '/user',
// `method` 是创建请求时使用的方法
method: 'get', // default
// baseURL+url形成最终发送请求的路径结果
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data, headers) {
// 对 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对 data 进行任意转换处理
return data;
}],
// `headers` 是请求头信息,有时候需要进行身份校验
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 用于传递参数
// 必须是一个无格式对象(plain object)或 URLSearchParams 对象
params: {
ID: 12345
},
// `paramsSerializer` 是一个负责 `params` 序列化的函数 (用得少)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` 是作为请求主体被发送的数据
// 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
// 在没有设置 `transformRequest` 时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
data: {
firstName: 'Fred'
},
data: 'Country=Brasil&City=Belo Horizonte',//data有以上两种形式分别是json格式和表单格式
// 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 1000, // default is `0` (no timeout)
// `withCredentials` 表示跨域请求时是否写到Cookie
withCredentials: false, // default
// `adapter` 允许自定义处理请求,以使测试更轻松
// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
//对请求的适配器做设置,两种:一种是AJAX,一种是在js中发送HTTP
adapter: function (config) {
/* ... */
},
// `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` 跨站请求标识,对cookie名字进行设置
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName`跨站请求标识,对头信息进行设置
xsrfHeaderName: 'X-XSRF-TOKEN', // default
//以上两个都是安全设置,保证请求来自自己的客户端,而不是来自未知其他页面,起到保护作用
/*
ps:为什么起到保护作用?
服务器在返回结果的时候会返回一个唯一标识,下一次再发送请求的时候需要把标识传回去,服务器认证没有问题才会响应
*/
// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
},
// `maxContentLength` 定义允许的响应内容的最大尺寸(字节)
maxContentLength: 2000,
//`validateStatus` 对响应结果的成功做设置,返回true就是成功
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` 定义在 node.js 中 follow 的最大重定向(跳转)数目
// 如果设置为0,将不会 follow 任何重定向
maxRedirects: 5, // default
// `socketPath` 设定Socket文件的位置,作用是向docker进程发送请求
socketPath: null, // default
// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
// `keepAlive` 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
//默认配置
axios.defaults.method = 'GET';//设置默认的请求类型为 GET
axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
axios.defaults.params = {id:100};
axios.defaults.timeout = 3000;
1-创建实例对象
const demo = axios.create({
baseURL: 'https://api.apiopen.top',
timeout: 2000
});
2-使用实例对象
duanzi({
url: '/getJoke',
}).then(response => {
console.log(response);
});
duanzi.get('/getJoke').then(response => {
console.log(response.data)
})
拦截器就是一些函数
在请求或相应被then
或catch
处理前拦截它们
1.拦截器的结构和正常执行顺序
//与Promise相关
// 添加请求拦截器 config就是配置项,结构参考上面的配置项说明
axios.interceptors.request.use(function (config) {
console.log("请求拦截器 成功");
return config;
}, function (error) {
// 对请求错误做些什么
console.log("请求拦截器 失败");
return Promise.reject(error);
});
// 添加响应拦截器 responce详情参考上面的响应结构
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('自定义回调处理成功的结果');
})
2.当请求拦截器发现参数出现问题时
//与Promise相关
// 添加请求拦截器 config就是配置项,结构参考上面的配置项说明
axios.interceptors.request.use(function (config) {
console.log("请求拦截器 成功");
throw '参数出问题';
}, function (error) {
// 对请求错误做些什么
console.log("请求拦截器 失败");
return Promise.reject(error);
});
// 添加响应拦截器 responce详情参考上面的响应结构
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('自定义回调处理成功的结果');
}).catch(response =>{
console.log('自定义失败回调');
})
3.当拥有两个拦截器,执行顺序是:请求拦截器后进先执行,响应拦截器先进先执行
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
console.log("请求拦截器 成功 1号");
return config;
}, function (error) {
console.log("请求拦截器 失败 1号");
return Promise.reject(error);
});
axios.interceptors.request.use(function (config) {
console.log("请求拦截器 成功 2号");
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('自定义回调处理成功的结果');
}).catch(response =>{
console.log('自定义失败回调');
})
4.了解config参数和response参数
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
console.log("请求拦截器 成功");
//修改config中的参数
config.params={a:100};
config.timeout=2000;
return config;
}, function (error) {
console.log("请求拦截器 失败");
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
console.log("响应拦截器 成功");
//只想得到响应体data
return response.data;
}, function (error) {
console.log("响应拦截器 失败");
return Promise.reject(error);
});
//发送请求
axios({
method : 'GET',
url:'http://localhost:3000/posts'
}).then(response =>{
console.log('自定义回调处理成功的结果');
//输出得到的response
console.log(response);
}).catch(response =>{
console.log('自定义失败回调');
})
结果只得到了请求体
官网示例:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
});
// cancel the request
cancel();
第一个按钮:发送请求
第二个按钮:取消请求
//获取按钮
const btns = document.querySelectorAll('button');
//2.声明全局变量
let cancel = null;
//发送请求
btns[0].onclick = function(){
//检测上一次的请求是否已经完成,如果没有完成直接取消重新发送
if(cancel !== null){
//取消上一次的请求
cancel();
}
axios({
method: 'GET',
url: 'http://localhost:3000/posts',
//1. 添加配置对象的属性
cancelToken: new axios.CancelToken(function(c){
//3. 将 c 的值赋值给 cancel
cancel = c;
})
}).then(response => {
console.log(response);
//将 cancel 的值初始化
cancel = null;
})
}
//绑定第二个事件取消请求
btns[1].onclick = function(){
cancel();
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。