1.xhr
2.jqeury(对xhr的封装)
3.axios (常用)(对xhr的封装)
4.fetch(与xhr平级)(promise风格)(两层promise)(兼容性差)
5.jsonp只能解决get请求
6.vue-resource
配置代理服务器
解决跨域问题
目前两个服务器
http://localhost:5000/students http://localhost:5001/cars
实现
配置的代理服务器与当前所处端口(8080)一致,将请求发送至代理服务器,由代理服务器向5000端口服务器转发。
(代理服务器与5000端口服务器打交道用的最传统的http请求)
借助vue-cli开启代理服务器
方式一:
vue.config.js
文件
module.exports = {
pages:{
index:{
//入口
entry: 'src/main.js',
},
},
lintOnSave:false, //关闭语法检查
//开启代理服务器 将请求转发给5000
devServer: {
proxy: 'http://localhost:5000'
}
发送请求
axios.get('http://localhost:8080/students').then( //向代理服务器发送
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败',error.message) //错误的原因
}
)
优点:配置简单,请求资源时直接发给前端(8080)
缺点:不能配置多个代理,不能灵活的控制是否走代理
工作方式:当请求了前端不存在的资源时,该请求会转发给服务器(优先匹配前端资源)
(public
文件内的东西都算8080有的,当请求的资源8080本身就有,就不会把请求转发给5000)
方式二:
可解决上述问题
vue.config.js
文件
module.exports = {
pages:{
index:{
//入口
entry: 'src/main.js',
},
},
lintOnSave:false, //关闭语法检查
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000',
//重写路径
pathRewrite:{'^/api':''},
ws: true, //用于支持websocket
changeOrigin: true //请求来自5000 说谎了
//用域控制请求头的host值
},
'/demo': {
target: 'http://localhost:5001',
//重写路径
pathRewrite:{'^/demo':''},
ws: true, //用于支持websocket
changeOrigin: true
}
}
}
}
注:
重写路径:由于服务器不存在/api/students
,需要重写路径,将/api
去除。
changeOrigin
:changeOrigin
的取值为true
(默认值)时,服务器收到的请求头中host来自localhost:5000
,与服务器端口一致(实际上来自8080,服务器说谎啦)
/api
:请求前缀 即可代理 可改变,匹配所有以‘/api’
开头的请求路径
发送请求
axios.get('http://localhost:8080/api/students').then(
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败',error.message) //错误的原因
}
)
axios.get('http://localhost:8080/demo/cars').then(
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败',error.message) //错误的原因
}
)
注:
/api
请求前缀放置在端口号后
缺点:请求资源时必须加前缀