Axios的学习
学习axios的原因: axios是我们的一个热门的前端ajax的前端向后端发送请求的库
首先学习axios的时候,首先先了解我们的Ajax和promise的基本内容
// 首先我们先来Ajax像后端发送请求的简单代码
// 先创建出Ajax对象
let xhr = new XMLHttpRequest();
// 然后向目标发送请求
xhr.open("get", "htttp://www.baidu.com/")
// 发送消息
xhr.send(null)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
console.log(JSON.parse(xhr.responseText))
}
}
}
// 创建 XMLHttpRequest 对象
let xhr = new XMLHttpRequest();
// 配置请求(方法、URL)
// 注意:确保 URL 是完整的,或者正确地相对于当前页面
xhr.open("GET", "http://example.com/api/xuyao");
// 发送请求(对于 GET 请求,send 方法的参数是 null)
xhr.send(null);
// 处理请求状态的变化
xhr.onreadystatechange = function() {
// 检查请求是否完成且成功(readyState 4 表示完成,status 2xx 表示成功)
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// 尝试将响应文本解析为 JSON
try {
const responseData = JSON.parse(xhr.responseText);
console.log(responseData);
} catch (error) {
// 如果不是有效的 JSON,则打印错误
console.error("无法解析 JSON:", xhr.responseText, error);
}
} else {
// 处理错误情况(如 404, 500 等)
console.error("请求失败,状态码:", xhr.status);
}
}
};
// 同时我们还是可以抽象成函数的
json_server的介绍
首先我们先实现介绍这个:是因为这个的话,是可以完成基本的那个于服务器之间搭建的一个模块
就是实现基本的创建假的服务器的一个服务
基本的使用步骤:
npm install json-server -g
然后创建一个虚拟的json数据文件db.json
{
"posts":[
{
"id":1,
"title":"json-server",
"author":"coppiced"
}
],
"comments":[
{
"id":1,
"body":"some comment",
"postId":1
}
],
"profile":{
"name":"typicality"
}
}
最后就是实现启动服务:json-server --watch db.json
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
// 通过修改我们的参数可以实现基本的那个访问不同的地方
http://localhost:3000/posts?id=1
http://localhost:3000/comments?id=1
http://localhost:3000/profile?name="typicality"
认识axios
axios是一个基于promise的http客户端,这个是可以实现基本的在node.js和浏览器两个端口运行
浏览器端可以通过axios向浏览器端实现向我们的服务端发送ajax请求
axios的特点:
1.可以在浏览器端发送ajax请求
2.可以在node.js中实现发送http请求
3.可以支持使用promise
4.对请求和响应体做一些基本的提前的工作
5.实现对请求和响应数据做一个转换
6.取消请求
8.实现基本的自动将数据转换为json数据
9.保护客户端的跨段攻击
安装axios:
项目中的使用方式:
npm isntall axios
yarn add axios
学习阶段:
<script src="https://cdn.jsdeliver.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs//axios/0.21.1/axios.min.js"></script>
<!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>Document</title>
</head>
<script src="https://cdn.bootcdn.net/ajax/libs//axios/0.21.1/axios.min.js"></script>
<body>
<script>
console.dir(axios)
</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>Document</title>
</head>
<script src="https://cdn.bootcdn.net/ajax/libs//axios/0.21.1/axios.min.js"></script>
<body>
<script>
window.onload = function(){
// 首先先获取事件
const getbtn = document.getElementById("get")
const postbtn = document.getElementById("post")
const putbtn = document.getElementById("put")
const deletebtn = document.getElementById("delete")
// 开始我们的get请求
getbtn.onclick = function(){
axios({
// 请求类型
method:"GET",
// 请求路径
url:"http://localhost:3000/posts?id=2"
}).then(value=>{
console.log(value)
})
},
// 实现添加一篇文章
// 实现我们的post请求
postbtn.onclick = function(){
axios({
method:"POST",
url:"http://localhost:3000/posts",
// 设置请求体
data:{
title:"2024年的高考新生",
auther:"76433"
}
})
}
// 实现我们的put请求
putbtn.onclick = function(){
axios({
method:"PUT",
url:"http://localhost:3000/posts/1",
auther:"433"
}).then(value=>{
console.log(value)
})
}
//开始完成delete请求
deletebtn.onclick = function(){
axios({
method:"DELETE",
url:"http://localhost:3000/posts/2"
})
}
}
</script>
<div>
<button id="get">发送get请求</button>
<button id="post">发送post请求</button>
<button id="put">发送put请求</button>
<button id="delete">发送delete请求</button>
</div>
</body>
</html>
axios的其他设置方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://cdn.bootcdn.net/ajax/libs//axios/0.21.1/axios.min.js"></script>
<body>
<script>
window.onload = function(){
const getbtn = document.getElementById("get")
const postbtn = document.getElementById("post")
const putbtn = document.getElementById("put")
const deletebtn = document.getElementById("delete")
//开始使用axios的其他请求的方式
// axios.request(config)
getbtn.onclick = function(){
axios.request({
method:"GET",
url:"http://localhost:3000/posts"
}).then(value=>{
console.log(value)
})
}
// 使用这个方法来实现发送post请求
postbtn.onclick = function(){
axios.post("http://localhost:3000/comments",
{
"body":"ndsjfn",
"postID":"sdjfhiowse"
}).then(value =>{
console.log(value)
})
}
}
</script>
<button id="get">发送get请求</button>
<button id="post">发送post请求</button>
<button id="put">发送put请求</button>
<button id="delete">发送delete请求</button>
</body>
</html>
<!--
axios.request(config)
axios.get(url[,config])
axios.post(url[,config])
axios.put(url[data,config])
axios.get(delete[,config])
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios.getUri([config])
-->
剖析axios的响应结构
config:就是我们的请求的时候的对象、
data:就是我们的响应体的对象,注意我们的axios实现的是自动的转换json数据格式为Object
headers:就是我们的响应头信息
request:就是我们的原生的ajax的请求对象,status是我们的响应状态码,statusTest就是我们的响应的状态的描述
axios的配置对象request config
url:就是指明我们到底是给谁发送请求,这个的话就是我们的路由选项
method:就是设置我们的发送请求的基本的方法
baseURL:就是设置的我们的基础的域名是什么,这个就是我们的基本的那个路由
headers:就是设置我们的请求头参数
transformRequest/transformResponse
params:设置请求的时候的参数,是一个对象
{
// `url` is the server URL that will be used for the request
url: '/user',
// `method` is the request method to be used when making the request
method: 'get', // default
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/',
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
},
// `paramsSerializer` is an optional config that allows you to customize serializing `params`.
paramsSerializer: {
//Custom encoder function which sends key/value pairs in an iterative fashion.
encode?: (param: string): string => { /* Do custom operations here and return transformed string */ },
// Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.
serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
//Configuration for formatting array indexes in the params.
indexes: false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes).
},
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer, FormData (form-data package)
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` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.
timeout: 1000, // default is `0` (no timeout)
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default
// `adapter` allows custom handling of requests which makes testing easier.
// Return a promise and supply a valid response (see lib/adapters/README.md)
adapter: function (config) {
/* ... */
},
// Also, you can set the name of the built-in adapter, or provide an array with their names
// to choose the first available in the environment
adapter: 'xhr' // 'fetch' | 'http' | ['xhr', 'http', 'fetch']
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
// Please note that only HTTP Basic auth is configurable through this parameter.
// For Bearer tokens and such, use `Authorization` custom headers instead.
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
// browser only: 'blob'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
// Note: Ignored for `responseType` of 'stream' or client-side requests
// options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
// 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
// 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
responseEncoding: 'utf8', // default
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `undefined` (default) - set XSRF header only for the same origin requests
withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),
// `onUploadProgress` allows handling of progress events for uploads
// browser & node.js
onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
// Do whatever you want with the Axios progress event
},
// `onDownloadProgress` allows handling of progress events for downloads
// browser & node.js
onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
// Do whatever you want with the Axios progress event
},
// `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
maxContentLength: 2000,
// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
maxBodyLength: 2000,
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
// If set to 0, no redirects will be followed.
maxRedirects: 21, // default
// `beforeRedirect` defines a function that will be called before redirect.
// Use this to adjust the request options upon redirecting,
// to inspect the latest response headers,
// or to cancel the request by throwing an error
// If maxRedirects is set to 0, `beforeRedirect` is not used.
beforeRedirect: (options, { headers }) => {
if (options.hostname === "example.com") {
options.auth = "user:password";
}
},
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default
// `transport` determines the transport method that will be used to make the request. If defined, it will be used. Otherwise, if `maxRedirects` is 0, the default `http` or `https` library will be used, depending on the protocol specified in `protocol`. Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol, which can handle redirects.
transport: undefined, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the hostname, port, and protocol of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
// variable as a comma-separated list of domains that should not be proxied.
// Use `false` to disable proxies, ignoring environment variables.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
proxy: {
protocol: 'https',
host: '127.0.0.1',
// hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
}),
// an alternative way to cancel Axios requests using AbortController
signal: new AbortController().signal,
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true, // default
// `insecureHTTPParser` boolean.
// Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
// This may allow interoperability with non-conformant HTTP implementations.
// Using the insecure parser should be avoided.
// see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
// see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
insecureHTTPParser: undefined, // default
// transitional options for backward compatibility that may be removed in the newer versions
transitional: {
// silent JSON parsing mode
// `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
// `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
silentJSONParsing: true, // default value for the current Axios version
// try to parse the response string as JSON even if `responseType` is not 'json'
forcedJSONParsing: true,
// throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
clarifyTimeoutError: false,
},
env: {
// The FormData class to be used to automatically serialize the payload into a FormData object
FormData: window?.FormData || global?.FormData
},
formSerializer: {
visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
dots: boolean; // use dots instead of brackets format
metaTokens: boolean; // keep special endings like {} in parameter key
indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
},
// http adapter only (node.js)
maxRate: [
100 * 1024, // 100KB/s upload limit,
100 * 1024 // 100KB/s download limit
]
}
// 官方文档描述
axios默认配置
就是使用一个语句即可
axios,defaults.method = "GET" // 设置的默认的请求类型为GET
axios.defaults.baseURL = "http://localhost:3000/" // 设置默认的url路径
axios.defaults.timeout = 3000 // 设置默认的加载时间
axios设置实例对象
const Ao = axios.create({
// 这个里面就是设置的我们的config的
baseURL:"http://localhost:3000",
timeout:2000
})
Ao.get("/posts").then(value =>{
console.log(value)
})
axios拦截器 Interceptors
拦截器就是我们一个函数,含有两中拦截器,一种就是请求拦截器,一种就是响应拦截器
请求拦截器就是实现基本的功能:就是在发送请求的时候,如果不行的话,那就直接拦截请求的过程
响应拦截器就是实现的我们的基本的一些功能:就是在我们的响应的过程中给如果出现错误,直接中断响应
首先我们的拦截器的话,就是传入的是回调函数,通过我们的回调函数来实现基本的那个功能
// 请求拦截器
axios.interceptors.request.use(function(config){
// console.log(config)
console.log("请求拦截器 未发现错误")
return config
}, function(error){
console.log("请求拦截器 发现错误")
return Promise.reject(error)
})
// 响应拦截器
axios.interceptors.response.use(function(response){
// console.log(response)
console.log("响应拦截器 未发现错误")
return response
}, function(error){
console.log("响应拦截器 发现错误")
return Promise.reject(error)
})
// 开始实现创建我们的请求实例化
const ax = axios.create({
baseURL:"http://localhost:300",
timeout:3000
})
ax.get("/posts").then(value => {
console.log(value)
}).catch(e){
console.log(e)
}
axios取消请求
let cancel = null
btn.onclick = function(){
// 开始实现检测我们的是否上一次的请求是否完成
if(cancel !== null){
cancel()
}
axios.get("http://localhost:3000",{
cancelToken:new axios.CancelToken(function(ct){
// 将ct的值赋值给cancel
cancel = ct
})
}).then(value=>{
console.log(value)
cancel = null
})
}
btn01.onclick = function(){
cancel()
}
// 为了体现出来我们的延时响应,可以在启动的时候设置: json-server --watch 文件名.json -d/--delay 2000
let cancel = null;
const btn = document.getElementById('your-button-id'); // 确保这是正确的 ID
const btn01 = document.getElementById('your-cancel-button-id'); // 确保这是正确的 ID
btn.onclick = function() {
if (cancel !== null) {
cancel('Request canceled by the user.'); // 您可以传递一个消息给取消函数(虽然这里 Axios 不直接使用它)
}
axios.get("http://localhost:3000", {
cancelToken: new axios.CancelToken(function executor(ct) {
cancel = ct;
})
}).then(value => {
console.log(value);
cancel = null; // 请求完成后重置 cancel
}).catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
} else {
// 处理其他类型的错误
console.error('There was an error!', error);
}
});
};
btn01.onclick = function() {
if (cancel !== null) {
cancel('Request canceled by the user.');
} else {
console.log('No request to cancel.');
}
};