Vue axios发送请求
Vue发送请求
- 下载axios插件
npm install axios -S
具体操作:
function get(){
// 请求地址,参数,请求头; then 是处理返回结果
axios.get("http://localhost:8080/hello",{
params:{
},
headers:{}
}).then(res => console.log(res));
}
function post(){
// 请求地址,请求体,补充信息; then 是处理返回结果
axios.post("http://localhost:8080/post",
{
//请求体的内容
name:"zhangsan",
age:18
},
{
//请求头的内容
params:{},
headers:{}
}
)
.then(res => console.log(res))//成功
.catch(err => console.log(err)); //失败
}
//put和delete也差不多
axios的封装
在src目录下创建 util目录,在util目录下创建request.js文件
import axios from 'axios'
// 设置超时时间
axios.defaults.timeout = 5000
// 创建axios实例
const util = axios.create({
baseURL: 'http://localhost:7082', // 前缀
timeout: 60000, // 请求超时时间毫秒
headers: {
'Content-Type': 'application/json',
},
})
export default util
export function get(url,params){
return util.get(url, {params: params});
}
export function post(url, data) {
return util.post(url, data);
}
export function del(url){
return util.delete(url);
}
export function put(url, data){
return util.put(url, data);
}
在其他文件使用,比如使用get方法
import {get} from '@/util/request'
这里只是封装了一个工具类,那么其他服务如果想要有自己的请求也可以写一个js,然后调用。