Axios 是一个基于 promise 网络请求库,作用于node.js
和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http
模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
请求地址
url: ‘/user’,
请求类型
method: ‘get’,
请根路径
baseURL: ‘http://www.mt.com/api’,
请求前的数据处理
transformRequest:[function(data){}],
请求后的数据处理
transformResponse: [function(data){}],
自定义的请求头
headers:{‘x-Requested-With’:‘XMLHttpRequest’},
URL查询对象
params:{ id: 12 },
查询对象序列化函数
paramsSerializer: function(params){ }
请求体
data: { key: ‘aa’},
超时设置
timeout: 1000,
第一种方式: 使用npm
npm install axios
第二种方式: 使用cdn
第三种方式: 使用yarn
yarn add axios
npm install axios
import axios from 'axios'
const app = createApp(App);
//使用axios, 并把axios作为app的全局属性
app.config.globalProperties.$axios=axios;
app.mount('#app')
this.$axios.get("https://autumnfish.cn/cloudsearch?keywords=" + this.query).then(function(response) {console.log(response)that.musicList = response.data.result.songs;}, function(err) {});
安装qs
npm install qs
在src目录下创建一个utils目录,用于存放一些工具的js文件, 在这个目录下我们创建一个request.js用于封装axios
import axios from 'axios'
import qs from 'qs'
/*** axios的传参方式:* 1.url 传参 一般用于Get和Delete 实现方式:config.params={JSON}* 2.body传参 实现方式:config.data = {JSON},且请求头为:headers: { 'Content-Type': 'application/json;charset=UTF-8' }* 3.表单传参 实现方式:config.data = qs.stringify({JSON}),且请求头为:且请求头为:headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }*/
// axios实例
const $http = axios.create({baseURL: '',timeout: 60000,headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})// 请求拦截器
$http.interceptors.request.use((config) => {// 追加时间戳,防止GET请求缓存if (config.method?.toUpperCase() === 'GET') {config.params = { ...config.params, t: new Date().getTime() }}if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {config.data = qs.stringify(config.data)}return config},error => {return Promise.reject(error)}
)// 响应拦截器
$http.interceptors.response.use(response => {const res = response.datareturn res},error => {return Promise.reject(error)}
)// 导出 axios 实例
export default $http
在main.js中,把$http绑定到app对象上
// 导入封装好的axios并挂载到Vue全局属性上
import $http from './utils/request'
app.config.globalProperties.$http = $http
使用:
methods: {sendAjax(){this.$http.get("https://autumnfish.cn/cloudsearch?keywords=" + this.query).then(function(response) {console.log(response)}, function(err) {});}},