json-server的介绍与服务搭建
安装
安装: npm install -g json-server
启动服务:json-server --watch db.json (db.json是起的文件名,在文件所在文件夹目录下启动)
文件内容实例
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
服务启动后可以通过地址 http://localhost:3000/posts/1, 得到以下数据
{ "id": 1, "title": "json-server", "author": "typicode" }
请求类型
GET /posts
GET /posts/1
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
Axios的理解
axios是什么
1. 前端最流行的 ajax 请求库
2. react/vue 官方都推荐使用 axios 发 ajax 请求
3. 文档: https://github.com/axios/axios
axios的特点
1. 基于 xhr + promise 的异步 ajax 请求库
2. 浏览器端/node 端都可以使用
3. 支持请求/响应拦截器
4. 支持请求取消
5. 请求/响应数据转换
6. 批量发送多个请求
axios常用语法
axios(config): 通用/最本质的发任意类型请求的方式
axios(url[, config]): 可以只指定 url 发 get 请求
axios.request(config): 等同于 axios(config)
axios.get(url[, config]): 发 get 请求
axios.delete(url[, config]): 发 delete 请求
axios.post(url[, data, config]): 发 post 请求
axios.put(url[, data, config]): 发 put 请求
axios.defaults.xxx: 请求的默认全局配置
axios.interceptors.request.use(): 添加请求拦截器
axios.interceptors.response.use(): 添加响应拦截器
axios.create([config]): 创建一个新的 axios(它没有下面的功能)
axios.Cancel(): 用于创建取消请求的错误对象
axios.CancelToken(): 用于创建取消请求的 token 对象
axios.isCancel(): 是否是一个取消请求的错误
axios.all(promises): 用于批量执行多个异步请求
axios.spread(): 用来指定接收所有成功数据的回调函数的方法
Axios使用
axios基本使用
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>axios基本使用</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>
<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',
//URL
url: 'http://localhost:3000/posts/2',
}).then(response => {
console.log(response);
});
}
//添加一篇新的文章
btns[1].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'POST',
//URL
url: 'http://localhost:3000/posts',
//设置请求体
data: {
title: "今天天气不错, 还挺风和日丽的",
author: "张三"
}
}).then(response => {
console.log(response);
});
}
//更新数据
btns[2].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'PUT',
//URL
url: 'http://localhost:3000/posts/3',
//设置请求体
data: {
title: "今天天气不错, 还挺风和日丽的",
author: "李四"
}
}).then(response => {
console.log(response);
});
}
//删除数据
btns[3].onclick = function(){
//发送 AJAX 请求
axios({
//请求类型
method: 'delete',
//URL
url: 'http://localhost:3000/posts/3',
}).then(response => {
console.log(response);
});
}
</script>
</body>
</html>
axios其他使用方法
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>axios其他使用</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>
<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');
//发送 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);
})
}
/**
* axios({
* url: '/post',
* // /post?a=100&b=200
* // /post/a/100/b/200
* // /post/a.100/b.200
* params: {
* a:100,
* b:200
* }
* })
*
*
*
*/
</script>
</body>
</html>
axios_的config配置对象
{
//url设置路径
url: '/user',
//method是发出请求时要使用的请求方法
method: 'get', // default
//baseURL将被放在' url '的前面,除非' url '是绝对的。
//为axios的实例设置' baseURL '可以方便地将相对url传递给该实例的方法。
baseURL: 'https://some-domain.com/api/',
//transformRequest允许在发送到服务器之前更改请求数据
//这只适用于请求方法'PUT', 'POST', 'PATCH'和'DELETE'
//数组中的最后一个函数必须返回一个字符串或Buffer、ArrayBuffer、FormData或Stream的实例
//你可以修改header对象。
transformRequest: [function (data, headers) {
// 做任何你想要转换数据的事情
return data;
}],
//transformResponse允许更改之前的响应数据
//它被传递给then/catch
transformResponse: [function (data) {
// 做任何你想要转换数据的事情
return data;
}],
//headers是要发送的自定义头,对请求头信息做配置
headers: {'X-Requested-With': 'XMLHttpRequest'},
//'params'是与请求一起发送的URL参数
//必须是一个普通对象或URLSearchParams对象
params: {
ID: 12345
},
// ' paramsSerializer '是一个负责序列化' params '的可选函数
//(例如https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// ' data '是要作为请求体发送的数据
//只适用于请求方法'PUT', 'POST', 'DELETE '和'PATCH'
//当没有设置' transformRequest '时,必须是以下类型之一:
//字符串,普通对象,ArrayBuffer, ArrayBufferView, URLSearchParams
// -浏览器:FormData, File, Blob
// -仅节点:流,缓冲区
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
// ' timeout '指定请求超时前的毫秒数。
//如果请求时间超过' timeout ',请求将被终止。
timeout: 1000, // default is `0` (no timeout)
// ' withCredentials '指示是否跨站点访问控制请求(是否跨域)
//应该使用凭据创建
withCredentials: false, // default
// ' adapter '允许自定义处理请求,使测试更容易。
//返回一个承诺并提供一个有效的响应(参见lib/adapters/README.md)。
adapter: function (config) {
/* ... */
},
// ' auth '表示应该使用HTTP Basic身份验证,并提供凭据。
//这将设置一个' Authorization '头,覆盖任何现有的
// ' Authorization '自定义头文件
//请注意,只有HTTP基本认证可通过该参数配置。
//对于不记名标记之类的,使用' Authorization '自定义头。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// ' responseType '表示服务器将响应的数据类型
//选项为:'arraybuffer', 'document', 'json', 'text', 'stream'
//仅浏览器:'blob'
responseType: 'json', // default
// ' responseEncoding '表示用于解码响应的编码(仅Node.js)
//注意:对于'stream'或客户端请求的' responseType '忽略
responseEncoding: 'utf8', // default
// ' xsrfCookieName '是要用作xsrf令牌值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
//' xsrfHeaderName '是携带xsrf令牌值的http报头的名称
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// ' onUploadProgress '只允许处理浏览器上传的进度事件
onUploadProgress: function (progressEvent) {
// 对原生进程事件做任何你想做的事
},
// ' onDownloadProgress '只允许处理下载浏览器的进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进程事件做任何你想做的事
},
// maxContentLength定义了node.js中允许的http响应内容的最大字节长度
maxContentLength: 2000,
// ' maxBodyLength '(节点唯一选项)定义http请求内容允许的最大字节大小
maxBodyLength: 2000,
// ' validateStatus '定义是解析还是拒绝给定的承诺
// HTTP响应状态码。 如果' validateStatus '返回' true '(或被设置为' null ')
//或' undefined '),承诺将被解析; 否则,承诺将是
//拒绝。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// ' maxRedirects '定义了node.js中要遵循的最大重定向数量。(最大跳转次数)
//如果设置为0,则不执行重定向。
maxRedirects: 5, // default
// ' socketPath '定义要在node.js中使用的UNIX套接字。
//。 ' / var /运行/码头工人。 向docker守护进程发送请求。
//只能指定' socketPath '或' proxy '。
//如果两者都指定,则使用' socketPath '。
socketPath: null, // default
// ' httpAgent '和' httpAgent '定义一个自定义代理用于执行http
//和HTTPS请求,分别在node.js。 这允许添加选项
//默认不启用的keepAlive。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// ' proxy '定义了代理服务器的主机名、端口和协议。
//你也可以使用传统的' http_proxy '和
// ' https_proxy '环境变量。 如果您正在使用环境变量
//你的代理配置,你也可以定义一个' no_proxy '环境
//变量作为一个逗号分隔的域列表,不应该被代理。
//使用' false '禁用代理,忽略环境变量。
// ' auth '表示HTTP基本认证应该用于连接到代理,并且
//供应凭证。
//这将设置一个' Proxy-Authorization '头,覆盖任何现有的
// ' Proxy-Authorization '自定义头文件
//如果代理服务器使用HTTPS,则必须将协议设置为' HTTPS '。
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// ' cancelToken '指定一个可以用来取消请求的取消令牌
//(详情见下面的取消部分)
cancelToken: new CancelToken(function (cancel) {
}),
// ' decompress '表示是否应该解压缩响应体
//自动。 如果设置为' true '也将删除'content-encoding'头
//从所有解压缩响应的响应对象
// -只有节点(XHR不能关闭解压缩)
decompress: true, // default
//在新版本中,向后兼容的过渡选项可能会被删除
transitional: {
//静默JSON解析模式
// ' true ' -忽略JSON解析错误并设置响应。 如果解析失败,数据将为空(旧行为)
// ' false ' -如果JSON解析失败抛出SyntaxError(注意:responseType必须设置为' JSON ')
silentJSONParsing: true, //当前Axios版本的默认值
//尝试将响应字符串解析为JSON,即使' responseType '不是' JSON '
forcedJSONParsing: true,
// 在请求超时时抛出ETIMEDOUT错误而不是一般的ECONNABORTED错误
clarifyTimeoutError: false,
}
}
axios的默认配置
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>axios基本使用</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>
<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');
//默认配置
axios.defaults.method = 'GET';//设置默认的请求类型为 GET
axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
axios.defaults.params = {id:100};
axios.defaults.timeout = 3000;//
btns[0].onclick = function(){
axios({
url: '/posts'
}).then(response => {
console.log(response);
})
}
</script>
</body>
</html>
axios创建实例对象
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>axios实例对象对象</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>
<div class="container">
<h2 class="page-header">基本使用</h2>
<button class="btn btn-primary"> 发送GET请求 </button>
<button class="btn btn-warning" > 发送POST请求 </button>
<br>
</div>
<script>
//获取按钮
const btns = document.querySelectorAll('button');
//创建实例对象 /getJoke
const duanzi = axios.create({
baseURL: 'https://api.apiopen.top',
timeout: 2000
});
// 如果有两个域名,就需要再写一个
const onather = axios.create({
baseURL: 'https://b.com',
timeout: 2000
});
//这里 duanzi 与 axios 对象的功能几近是一样的
// duanzi({
// url: '/getJoke',
// }).then(response => {
// console.log(response);
// });
duanzi.get('/getJoke').then(response => {
console.log(response.data)
})
</script>
</body>
</html>
axios_拦截器(Interceptors)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拦截器</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
<script>
// Promise
// 设置请求拦截器 config 配置对象
axios.interceptors.request.use(function (config) {
console.log('请求拦截器 成功 - 1号');
//修改 config 中的参数
config.params = {a:100};
return config;
}, function (error) {
console.log('请求拦截器 失败 - 1号');
return Promise.reject(error);
});
axios.interceptors.request.use(function (config) {
console.log('请求拦截器 成功 - 2号');
//修改 config 中的参数
config.timeout = 2000;
return config;
}, function (error) {
console.log('请求拦截器 失败 - 2号');
return Promise.reject(error);
});
// 设置响应拦截器
axios.interceptors.response.use(function (response) {
console.log('响应拦截器 成功 1号');
return response.data;
// 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('自定义回调处理成功的结果');
console.log(response);
});
</script>
</body>
</html>
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: process.env.BASE_API, // api 的 base_url
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// Do something before request is sent
if (store.getters.token) {
// 让每个请求携带token-- ['X-Dts-Admin-Token']为自定义key 请根据实际情况自行修改
config.headers['X-Dts-Admin-Token'] = getToken()
}
return config
},
error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (res.errno === 501) {
MessageBox.alert('系统未登录,请重新登录', '错误', {
confirmButtonText: '确定',
type: 'error'
}).then(() => {
store.dispatch('FedLogOut').then(() => {
location.reload()
})
})
return Promise.reject('error')
} else if (res.errno === 502) {
MessageBox.alert('系统内部错误,请联系管理员维护', '错误', {
confirmButtonText: '确定',
type: 'error'
})
return Promise.reject('error')
} else if (res.errno === 503) {
MessageBox.alert('请求业务目前未支持', '警告', {
confirmButtonText: '确定',
type: 'error'
})
return Promise.reject('error')
} else if (res.errno === 504) {
MessageBox.alert('更新数据已经失效,请刷新页面重新操作', '警告', {
confirmButtonText: '确定',
type: 'error'
})
return Promise.reject('error')
} else if (res.errno === 505) {
MessageBox.alert('更新失败,请再尝试一次', '警告', {
confirmButtonText: '确定',
type: 'error'
})
return Promise.reject('error')
} else if (res.errno === 506) {
MessageBox.alert('没有操作权限,请联系管理员授权', '错误', {
confirmButtonText: '确定',
type: 'error'
})
return Promise.reject('error')
} else if (res.errno !== 0) {
// 非5xx的错误属于业务错误,留给具体页面处理
return Promise.reject(response)
} else {
return response
}
}, error => {
console.log('err' + error)// for debug
Message({
message: '登录连接超时(后台不能连接,请联系系统管理员)',
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
})
export default service
axios取消请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>取消请求</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>
<div class="container">
<h2 class="page-header">axios取消请求</h2>
<button class="btn btn-primary"> 发送请求 </button>
<button class="btn btn-warning" > 取消请求 </button>
</div>
<script>
//获取按钮
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();
}
</script>
</body>
</html>
版权声明:本文为weixin_41452476原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。