Axios用法
学习来源:https://www.axios-http.cn/
一、基础用法
首先引入,我发现只有在网页的head标签里放入script标签,才会生效!
<head>
<!--使用CDN镜像文件-->
<script th:src="@{https://unpkg.com/axios/dist/axios.min.js}"></script>
</head>
这是心得:get或者post请求,都意味着Axios会与服务端的进行信息交互,可以传输数据到后台,同时获得从后台获得数据!最重要的是,不必刷新网页,而是局部数据更新,降低资源消耗。
可以摒弃以往的前端页面写后端语法的问题啦~
1、使用GET发送请求
标准写法
//使用axios发送有参的get请求
axios({
url:'http://localhost:8080/projectName/path',
method:'get', //默认也会使用get请求
params:{ //这个是附加传值,需要传入后端的值填写到这里,如没有则不写params
id:'1',
name:'张三'
}
}).then(function (response){ //获得后端传入的信息,包括数据,一般在response的data属性里
console.log(respinse.data);
}).catch(function(error){ //如果请求出现错误,则会运行此处,返回错误信息。
console.log(error)
})
简略写法:
//使用axios发送有参的get请求
axiso.get('http://localhost:8080/projectName/path' , { params:{id:1} })
.then(response=>{ console.log(response); })
.catch(error=>{ console.log(error); })
2、使用POST发送请求
标准写法:
//使用axios发送有参的请求
axios({
url:'http://localhost:8080/projectName/path',
method:'post',
data:{
name:'张三' //这样的写法,会传入后端是以json字符串的形式
"name=张三" //推荐这样写法,可以让后端方法,直接传入参数中(推荐)
}
}).then(function (response){
console.log(respinse.data);
}).catch(function(error){
console.log(error)
})
简略写法:
//使用axios发送有参的请求,发送的请求携带参数,直接使用"name=张三&age=10"
axiso.post('http://localhost:8080/projectName/path' , "name=张三&age=10" )
.then(response=>{ console.log(response); })
.catch(error=>{ console.log(error); })
//使用data传递数据的话,后台需要将axios自动转换json数据为java对象
axiso.post('http://localhost:8080/projectName/path' , {name:'张三',age:'10'} )
.then(response=>{ console.log(response); })
.catch(error=>{ console.log(error); })
//写成这样,后台spring mvc处理方式,给参数加上注解@RequestBody
@PostMapping("/projectName/path")
public String findStudenByName( @RequestBody Student student ){
String name = student.getName();
String age = student.getAge();
...
return;
}
//需要说明的是post传参是name和age,用Student类接受,是因为,这两个属性是Student类内的属性,所以可以传入。
总结:
后台控制器接受到的name 为null,是因为axios使用post携带参数请求默认使用application/json
解决方法一:params属性进行数据的传递
解决方法二:"name=张三"
解决方法三:服务器端给接受的参数加上@requesBody
3、发送文件和获得JSON值
个人项目中,需要上传Excel文件,所以用到了下面的代码,直接全部贴出来:
<script>
var demo = new Vue({
el: "#app",
data:{
fileInfo:[]
},
methods: {
fileUpload: function () {
console.log("fileUpload方法启动了!");
let self = this; //至关重要的一步!使得fuleUpload方法可以访问到实例!
//var _this = this;
var formData = new FormData(); //将上传的文件放入此变量中
formData.append("uploadFile", $("input[name='uploadFile']")[0].files[0]);
axios({
method: "post",
url: "/sxap/excelFile",
data: formData, //这里的data属性代表返回给后台的数据
headers: {
'Content-Type': 'multipart/form-data', // 文件上传,将文件设置为二进制格式传输
// 'Content-Type': 'application/x-www-form-urlencoded', // 表单
// 'Content-Type': 'application/json;charset=UTF-8' // json
},
}).then(function (response) {
self.fileInfo = response.data; //将后台返回的json字符串,传值给fileInfo
console.log(self.fileInfo);
}).catch(function (reason) {
console.log('发生了错误');
console.log(reason)
})
},
}
});
</script>
此处难点有两个:
- 如何将文件上传,利用axios的data属性,将要上传的excel文件转换为二进制格式进行上传。
- 如何将后台返回的json字符串,赋值给VUE实例内data里的变量!
主要时间浪费在了第二个问题上
axios获取不到函数外部变量
原因是:是在then的内部不能使用Vue的实例化的this, 因为在内部this没有被绑定。
解决方法如下:
- 定义this,使得方法内部可以使用
let self = this; //至关重要的一步!使得fuleUpload方法可以访问到实例!
self.fileInfo = response.data; //将后台返回的json字符串,传值给fileInfo
- 使用ES6的箭头函数arrow function,箭头方法可以和父方法共享变量 (未尝试)
axiso.post('...').then((res)=>{
this.fileInfo = response.data;
})
二、请求配置
这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 GET 方法。
{
// `url` 是用于请求的服务器 URL
url: '/user',
// `method` 是创建请求时使用的方法
method: 'get', // 默认值
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 它只能用与 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
// 你可以修改请求头。
transformRequest: [function (data, headers) {
// 对发送的 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对接收的 data 进行任意转换处理
return data;
}],
// 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是与请求一起发送的 URL 参数
// 必须是一个简单对象或 URLSearchParams 对象
params: {
ID: 12345
},
// `paramsSerializer`是可选方法,主要用于序列化`params`
// (e.g. 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` 时,则必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属: FormData, File, Blob
// - Node 专属: Stream, Buffer
data: {
firstName: 'Fred'
},
// 发送请求体数据的可选语法
// 请求方式 post
// 只有 value 会被发送,key 则不会
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout` 指定请求超时的毫秒数。
// 如果请求时间超过 `timeout` 的值,则请求会被中断
timeout: 1000, // 默认值是 `0` (永不超时)
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
// `adapter` 允许自定义处理请求,这使测试更加容易。
// 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
adapter: function (config) {
/* ... */
},
// `auth` HTTP Basic Auth
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示浏览器将要响应的数据类型
// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 浏览器专属:'blob'
responseType: 'json', // 默认值
// `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
// 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // 默认值
// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
xsrfCookieName: 'XSRF-TOKEN', // 默认值
// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
// `onUploadProgress` 允许为上传处理进度事件
// 浏览器专属
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `onDownloadProgress` 允许为下载处理进度事件
// 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},
// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
maxContentLength: 2000,
// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
maxBodyLength: 2000,
// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
// 则promise 将会 resolved,否则是 rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认值
},
// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
// 如果设置为0,则不会进行重定向
maxRedirects: 5, // 默认值
// `socketPath` 定义了在node.js中使用的UNIX套接字。
// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
// 只能指定 `socketPath` 或 `proxy` 。
// 若都指定,这使用 `socketPath` 。
socketPath: null, // 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` 定义了代理服务器的主机名,端口和协议。
// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// see https://axios-http.com/docs/cancellation
cancelToken: new CancelToken(function (cancel) {
}),
// `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 // 默认值
}
日常使用
Axios封装
为什么进行封装?
a.统一配置http请求baseURL,超时配置,请求头配置。。
b.可以劫持劫持响应,劫持请求,添加全局加载提示,添加header鉴权,响应错误统一处理
c.扩展简化axios方法jsonp, postURL
import axios from 'axios'
// 导入axios
import { Toast } from 'vant';
// 设置基础URL
import qs from 'qs';//-S
// qs把对象转换为url编码形式
const BASEURL = process.env.NODE_ENV==='production'?'https://www.520mg.com/':'http://localhost:8080';
// process.env.NODE_ENV 当前的运行环境是production
// process 处理 env环境 node NodeJS env 环境
// 当前的运行环境如果是线上 就业采用域名 https://www.520mg.com 作为所有请求的默认域名,如果开发环境则设置另外一个
// 创建一个axios实例
let request = axios.create({
baseURL:BASEURL, //基础url
timeout:3000,//请求超时
})
// 请求 拦截请求 添加token ,添加加载提示
// interceptors 拦截器
// request 拦截请求 use 使用
// config 请求配置 headers 请求头
// sessionStorage.getItem 本地会话存储
request.interceptors.request.use(
config=>{
Toast.loading({
message: '加载中...',
forbidClick: true,
loadingType: 'spinner',
});
config.headers.Token = sessionStorage.getItem("token");
return config
}
)
// 思考:指定加载提示,才提示,指定提示文本
// 响应拦截
request.interceptors.response.use(
res=>{
Toast.clear();
return res;
}
)
// 定义一个post方法 url 地址 data 数据
// 自动把对象转换为 url编码
// 添加了headers 头信息
request.postURL=function(url,data){
return new Promise((resolve,reject)=>{
request({
url:url,
data:qs.stringify(data),
method:"post",
headers:{"Content-Type":"application/x-www-form-urlencoded"}
})
.then(res=>resolve(res))
.catch(err=>reject(err))
})
}
export default request;
// 导出request
// 为什么需要二次封装 axios
// 1. 请求与响应拦截 请求前添加 loading,请求完毕移除loading
// 每个请求都要添加 token auth等权限凭据
// 2. 统一配置 :基本域名
// 3. 二次封装一些方法,jsonp postURL
调用
<template>
<div>
<h1>星球</h1>
</div>
</template>
<script>
/* 接收封装的东西 */
import request from '@/utils/request.js'
export default {
created(){
this.getJoks();
},
methods:{
getJoks(){
request.get(url)
.then(res=>{
console.log(res.data);
})
}
}
}
</script>
<style>
</style>

浙公网安备 33010602011771号