Vue——发送http请求详解
⼀、简介
1)vue本⾝不⽀持发送AJAX请求,需要使⽤vue-resource、axios等插件实现。
2) axios是⼀个基于Promise的HTTP请求客户端,⽤来发送请求,也是vue2.0官⽅推荐的,同时不再对vue-resource进⾏更新和维护。⼆、使⽤axios发送AJAX请求
1、安装axios并引⼊
1)npm的⽅式: $ npm install axios -S  或 cnpm install axios -S
2)bower的⽅式:$ bower install axios
2.如何引⼊使⽤axios
安装其他插件的时候,可以直接在 main.js 中引⼊并 Vue.use(),但是 axios 并不能 use,只能每个需要发送请求的组件中即时引⼊
为了解决这个问题,有两种开发思路,
⼀是在引⼊ axios 之后,修改原型链
⼆是结合 Vuex,封装⼀个 aciton
⽅案⼀:改写原型链
⾸先在 main.js 中引⼊ axios
import axios from'axios'
Vue.prototype.$http= axios
在组件中发送http请求
this.$http.post('/user',{name: 'xiaoming'})
this.$http({method: 'post',url: '/user',data: {name: 'xiaoming'}})
//发送get请求
this.$('/user?ID=12345')
.
then(res=> { console.log(response); })
.catch(err=> { console.log(error); });
this.$('/user',{params:{ID:12345}})
.then(res=> { console.log(response); })
.catch(err=> { console.log(error); });
//发送post请求
this.$http.post('/user',{name: 'xiaoming'})
.then(res=> { console.log(res) })
.catch(err=> { console.log(err)});
3.封装axios进⾏调⽤
/****  request.js  ****/
/
/ 导⼊axios
import axios from'axios'
// 使⽤element-ui Message做消息提醒
import { Message} from'element-ui';
//1. 创建新的axios实例,
const service = ate({
// 公共接⼝--这⾥注意后⾯会讲
baseURL: '',
// 超时时间单位是ms,这⾥设置了3s的超时时间
timeout: 3 * 1000
})
/
/ 2.请求
quest.use(config => {
//发请求前做的⼀些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
config.data = JSON.stringify(config.data); //数据转化,也可以使⽤qs转换
console.log('请求中',config)
config.headers = {
'Content-Type':'application/x-www-form-urlencoded'//配置请求头
}
//注意使⽤token的时候需要引⼊cookie⽅法或者⽤本地localStorage等⽅法,推荐js-cookie
// const token = getCookie('名称');//这⾥取token之前,你肯定需要先拿到token,存⼀下
// if(token){
/
/  config.params = {'token':token} //如果要求携带在参数中  //  ken= token; //如果要求携带在请求头中  // }
return config
}, error => {
console.log('错误')
})
// 3.响应
sponse.use(response => {
//接收到响应数据并成功后的⼀些共有的处理,关闭loading等return response
}, error => {
console.log('error',error)
/***** 接收到异常响应的处理开始 *****/
if (error && sponse) {
// 1.公共错误处理
// 2.根据响应码具体处理
switch (sponse.status) {
case400:
break;
case401:
break;
case403:
break;
case404:
// window.location.href = "/"
break;
case405:
break;
case408:
break;
case500:
break;
case501:
break;
case502:
break;
case503:
break;
case504:
break;
case505:
break;
default:
}
} else {
// 超时处理
if (JSON.stringify(error).includes('timeout')) {
<('服务器响应超时,请刷新当前页')
}
<('连接服务器失败')
}
<(ssage)
/***** 处理结束 *****/
//如果不需要错误处理,以上的处理过程都可省略
发送ajax请求的步骤
sponse)
})
//4.导⼊⽂件
export default service
/****  http.js  ****/
// 导⼊封装好的axios实例
import request from'./request'
const http ={
/**
* methods: 请求
* @param url 请求地址
* @param params 请求参数
*/
get(url,params){
const config = {
method: 'get',
url:url
}
if(params) config.params = params
return request(config)
},
post(url,params){
console.log(url,params)
const config = {
method: 'post',
url:url
}
if(params) config.data = params
return request(config)
},
put(url,params){
const config = {
method: 'put',
url:url
}
if(params) config.params = params
return request(config)
},
delete(url,params){
const config = {
method: 'delete',
url:url
}
if(params) config.params = params
return request(config)
}
}
//导出
export default http
import http from'./http'
//
/**
*  @parms resquest 请求地址例如:197.82.15.15:8088/request/...
*  @param '/testIp'代表vue-cil中config,index.js中配置的代理
*/
/
/ let resquest = ""
// get请求
export function getListAPI(resquest,params){
(`${resquest}/getList.json`,params)
}
// post请求
export function postFormAPI(resquest,params){
console.log('发送post请求')
return http.post(`${resquest}`,params)
}
// put 请求
export function putSomeAPI(resquest,params){
return http.put(`${resquest}/putSome.json`,params)
}
// delete 请求
export function deleteListAPI(resquest,params){
return http.delete(`${resquest}/deleteList.json`,params)
}
解决Vue跨域问题:
解决⽅法:在脚⼿架中的config下的index.js中
在 dev 的 proxyTable 对象中添加这些属性
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
"/api":{
target:"xin.yuemei/V603/channel/getScreenNew/",//接⼝域名
changeOrigin:true,//是否跨域
pathRewrite:{
"^/api":""//重写为空,这个时候api就相当于上⾯target接⼝基准地址        }
}
},
然后请求这⾥⽤axios请求
请求的时候前缀api就相当于基准地址了
axios.post("/api").then(res => {
console.log(res);
this.data = res.data.data;
});
//如果有参数请求
axios.post("/api?key=111").then(res => {
console.log(res);
this.data = res.data.data;
});
配置完记得重跑⼀下项⽬(切记)
想要发送Ajax请求通过两种⽅式
⼀:通过XHR对象
请求⾏:
method:post 或get  url:请求地址
请求头:
host:主机地址
cookie
content-type:请求体内容
请求体:
响应⾏:status
响应头:多个响应头
响应体:
json/图⽚/css/js/html
⼆:通过fetch函数