Vue.js3.0中请求后端数据
Vue.js3.0中请求后端数据有多种方式,其中最常用的是使用axios库,它是一个基于Promise的HTTP客户端,可以发送请求到后端服务器,并且拿到响应结果。
安装axios
在Vue.js中使用axios,需要安装它,可以使用npm安装:
npm install axios
发送get请求
在Vue.js中使用axios发送get请求,需要先引入axios:
import axios from 'axios'
就可以发送get请求了,发送get请求的代码如下:
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
发送post请求
在Vue.js中使用axios发送post请求,和发送get请求类似,只需要把get改为post即可:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
发送请求时带上头部信息
如果需要发送请求时带上头部信息,可以使用axios中的headers参数:
axios.get('/user', {
headers: {
'Authorization': 'Bearer token'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
发送请求时携带参数
如果需要发送请求时携带参数,可以使用axios中的params参数:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
发送请求时携带数据
如果需要发送请求时携带数据,可以使用axios中的data参数:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
发送请求时设置超时时间
如果需要发送请求时设置超时时间,可以使用axios中的timeout参数:
axios.get('/user', {
timeout: 1000
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
使用axios拦截器
axios提供了拦截器的功能,可以在发送请求之前和接收到响应之后做一些处理,比如设置请求头、添加请求参数等,使用axios拦截器的代码如下:
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
以上就是Vue.js3.0中请求后端数据的方法,主要是使用axios库发送请求,可以发送get、post请求,并且可以携带参数、头部信息、设置超时时间等,还可以使用axios拦截器做一些处理。