Vue——Axios_vue axios请求
一、Axios 是什么
Axios 是一个基于 promise 网络请求库,作用于 node.js 和浏览器中。 它是 isomorphic 的(即同一套代 码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使 用 XMLHttpRequests。 官网地址: https://www.axios-http.cn/
二、Axios的特性
- 从浏览器创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 超时处理
- 查询参数序列化支持嵌套项处理
- 自动将请求体序列化为:
- JSON ( application/json )
- Multipart / FormData ( multipart/form-data )
- URL encoded form ( application/x-www-form-urlencoded )
- 将 HTML Form 转换成 JSON 进行请求
- 自动转换JSON数据
- 获取浏览器和 node.js 的请求进度,并提供额外的信息(速度、剩余时间)
- 为 node.js 设置带宽限制
- 兼容符合规范的 FormData 和 Blob(包括 node.js)
- 客户端支持防御XSRF
三、安装
使用 npm:
$ npm install axios
四、请求方式
- 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.postForm(url[, data[, config]])
- axios.putForm(url[, data[, config]])
- axios.patchForm(url[, data[, config]])
详细介绍:
Axios 是一个基于 Promise 的 HTTP 客户端,广泛用于浏览器和 Node.js 环境中。它提供了多种请求方法,每种方法都有其特定的用途和参数配置。以下是这些请求方式的详细介绍:
axios.request(config)
axios.request(config)
是一个通用的请求方法,允许用户自定义请求的所有配置。config
参数是一个对象,包含了请求的 URL、方法、头信息、数据等。
axios.request({ method: \'get\', url: \'/user/12345\'});
axios.get(url[, config])
axios.get(url[, config])
用于发送 GET 请求。url
是请求的目标地址,config
是可选的配置对象。
axios.get(\'/user/12345\') .then(response => console.log(response.data));
axios.delete(url[, config])
axios.delete(url[, config])
用于发送 DELETE 请求。url
是请求的目标地址,config
是可选的配置对象。
axios.delete(\'/user/12345\') .then(response => console.log(\'User deleted\'));
axios.head(url[, config])
axios.head(url[, config])
用于发送 HEAD 请求。url
是请求的目标地址,config
是可选的配置对象。
axios.head(\'/user/12345\') .then(response => console.log(response.headers));
axios.options(url[, config])
axios.options(url[, config])
用于发送 OPTIONS 请求。url
是请求的目标地址,config
是可选的配置对象。
axios.options(\'/user/12345\') .then(response => console.log(response.data));
axios.post(url[, data[, config]])
axios.post(url[, data[, config]])
用于发送 POST 请求。url
是请求的目标地址,data
是请求体数据,config
是可选的配置对象。
axios.post(\'/user\', { firstName: \'John\', lastName: \'Doe\' }) .then(response => console.log(response.data));
axios.put(url[, data[, config]])
axios.put(url[, data[, config]])
用于发送 PUT 请求。url
是请求的目标地址,data
是请求体数据,config
是可选的配置对象。
axios.put(\'/user/12345\', { firstName: \'Jane\', lastName: \'Doe\' }) .then(response => console.log(response.data));
axios.patch(url[, data[, config]])
axios.patch(url[, data[, config]])
用于发送 PATCH 请求。url
是请求的目标地址,data
是请求体数据,config
是可选的配置对象。
axios.patch(\'/user/12345\', { firstName: \'Jane\' }) .then(response => console.log(response.data));
axios.postForm(url[, data[, config]])
axios.postForm(url[, data[, config]])
用于发送表单格式的 POST 请求。url
是请求的目标地址,data
是表单数据,config
是可选的配置对象。
axios.postForm(\'/user\', { firstName: \'John\', lastName: \'Doe\' }) .then(response => console.log(response.data));
axios.putForm(url[, data[, config]])
axios.putForm(url[, data[, config]])
用于发送表单格式的 PUT 请求。url
是请求的目标地址,data
是表单数据,config
是可选的配置对象。
axios.putForm(\'/user/12345\', { firstName: \'Jane\', lastName: \'Doe\' }) .then(response => console.log(response.data));
axios.patchForm(url[, data[, config]])
axios.patchForm(url[, data[, config]])
用于发送表单格式的 PATCH 请求。url
是请求的目标地址,data
是表单数据,config
是可选的配置对象。
axios.patchForm(\'/user/12345\', { firstName: \'Jane\' }) .then(response => console.log(response.data));
这些方法提供了灵活的方式来处理不同的 HTTP 请求,使得开发者能够根据具体需求选择合适的请求方式。
五、基本实例
导入axios:
import axios from \'axios\'
GET请求:
const doGet = ()=>{alert(\"Get\")// axios.get(\"url\",{}).then(函数).catch(函数)// promise 语法 .then .axios.get(\"https://apifoxmock.com/m1/5559918-5237013-default/news\",{// params 请求参数params:{cid:1},headers:{}})// 正常情况 使用then 接受结果.then((res)=>{console.log(res.data)})// 异常 使用catch处理.catch(reason=>{console.log(reason)})}
POST请求:
const doPost = ()=>{// post(\"url\",data,{})// axios.post(\"https://apifoxmock.com/m1/5559918-5237013-default/add\",{username:\"aaaa\",pwd:\"00000\"})// .then(res=>{// console.log(res.data)// alert(res.data.msg)// })// .catch(reason=>{// console.log(reason)// })axios.request({url:\"https://apifoxmock.com/m1/5559918-5237013-default/add\",data:{u:1,pwd:2},method:\"POST\",headers:{},params:{}})}
跨域:后端方案-配置允许跨域
@Configurationpublic class AccessControlAllowOriginConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping(\"/**\").allowedOriginPatterns(\"*\").allowedMethods(\"GET\", \"POST\", \"PUT\", \"DELETE\").allowCredentials(true).maxAge(3600).allowedHeaders(\"*\");}}
前端方案-本地服务器代理 项目目录中创建vue.config.js内容如下:
module.exports = {// 开发服务器devServer: {port: 8082, // 修改启动端口号proxy: {\'/api\': { // 请求相对路径以 /api 开头的,才会走这里的配置target: \'http://127.0.0.1:8080\', // 这个就是后端地址changeOrigin: true,pathRewrite: {\'^/api\': \'/\'}}
六、项目封装
src->util->request.js (全局配置)
import axios from \"axios\";// 全局配置const service = axios.create({// 请求的根路径:一般配置域名//实际的请求: baseUrl+urlbaseURL:\"https://apifoxmock.com/m1/5559918-5237013-default\",timeout:5000})export default service
每个页面都有很多请求,按照页面划分请求,src->api->页面名称.js ——index.js
import service from \"../util/request\";// 配置首页的所有请求// 首页中 获取新闻列表export function getNews(params){return service.request({url:\"/news\",params,method:\"GET\"})}// 首页 获取菜单列表export function getMenu(params){return service.get(\"/menu\",{params})}
页面中使用
const doGet1 = ()=>{getNews({cid:1}).then(res=>{console.log(res.data)})}
七、拦截
请求拦截:用于登录,所有登录的api 加上token。响应拦截:统一处理异常:登录失效等等。代码实例request.js
import axios from \"axios\";// 全局配置const service = axios.create({// 请求的根路径:一般配置域名//实际的请求: baseUrl+urlbaseURL:\"https://apifoxmock.com/m1/5559918-5237013-default\",timeout:5000})// 请求拦截service.interceptors.request.use(config => {console.log(\"请求拦截,所有请求先经过拦截器!!!!\")// 登录成功 将token 存入 localstorage// 所有请求 带token(用户标识)config.headers[\'token\'] = localStorage.getItem(\'usertoken\') || \'\';return config},error => {return Promise.reject(error)})// 响应拦截service.interceptors.response.use(response=>{if(response.data.code==\"30000\"){// token失效// route.push({url:\"/login\"})}},error=>{})export default service
(* ̄︶ ̄)——课堂笔记更新中...