解决开发环境ajax跨域问题
方法一:在vue.config.js中添加配置
devServer:{
proxy: "http://localhost:5000"
}
说明:
1.优点:配置简单,请求资源时直接发给前端(8080) 即呵。
2.缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
3.工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源<前端资源:public中的静态资源>)
方法二:编写vue.config.js配置具体代理原则
module. exports = {
devServer: {
proxy: {
'/api1': {// 匹配所有以'/api1'开头的请求路径
target: 'http://localhost:5000',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api1': "'}
},
'/api2': {// 匹配所有以'/api2'开头的请求路径
target: 'http://localhost:5001',//代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api2': ''}
}
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为: localhost: 5000
changeOrigin设置为false时,服务器收到的请求头中的host为: localhost : 8080
change0rigin默认值为true
*/
说明: .
1.优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
2.缺点:配置略微繁琐,请求资源时必须加前缀。
App组件
<template>
<div>
<button @click="getStudents">获取学生信息</button>
<button @click="getCars">获取汽车信息</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:'App',
methods: {
getStudents(){
axios.get('http://localhost:8080/atguigu/students').then(
response=>{
console.log('请求成功了',response.data);
},
error=>{
console.log('请求失败了',error.message);
}
)
},
getCars(){
axios.get('http://localhost:8080/demo/cars').then(
response=>{
console.log('请求成功了',response.data);
},
error=>{
console.log('请求失败了',error.message);
}
)
}
},
}
</script>
vue.config.js
// 开启代理服务器(方式一)
/* devServer: {
proxy: 'http://localhost:5000'
}, */
// 开启代理服务器(方式二)
devServer: {
proxy: {
'/atguigu': {
target: 'http://localhost:5000',
pathRewrite:{'^/atguigu':''},
ws: true,//用于支持websocket
changeOrigin: true//用于控制请求头中的host值
},
'/demo': {
target: 'http://localhost:5001',
pathRewrite:{'^/demo':''},
ws: true,//用于支持websocket
changeOrigin: true//用于控制请求头中的host值
},
/* '/foo': {
target: '<other_url>'
} */
}
}