Vue配置代理
Vue配置代理详解
·
为什么要使用代理:
为了解决Ajax请求跨域的问题(当前域名下的页面请求其它域名时会被浏览器拦截)。
跨域详解请参考:https://blog.csdn.net/qq_45334976/article/details/125113481
配置代理方法一(不推荐)
优点:简单方便配置
缺点:不灵活,不能配置多个代理,不能控制是否走代理,当public文件夹中有没有后缀名的文件与访问资源地址名相同时并不会转发,而是会把资源文件展示到页面
工作方式:当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)
vue.config.js中配置要转发的地址
module.exports = {
devServer: {
//转发到服务器的ip与端口
proxy: 'http://123.21.33.22:31'
}
}
Ajax请求,请求的url中地址配置为代理服务器的地址,把请求发给代理服务器后,代理服务器会查看public文件夹中是否有对应资源,有的话不进行转发,把本地资源发送给前端,如果没有,则进行转发。
axios.get("http://localhost:8080/student/getStudentsMsg").then(
response=>{
console.log("请求成功:",response.data)
},
error=>{
console.log("请求失败:",response.message)
}
)
配置代理方法二(推荐)
优点:可以配置多个代理,且可以灵活的控制请求是否走代理
缺点:配置略微繁琐,请求资源时必须加前缀
vue.config.js中配多个代理
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false, /*关闭语法检查*/
devServer: {
proxy: {
//匹配所有/student开头的请求进行转发
'/student': {
target: 'http://localhost:31',
//pathRewrite:{'^/student':''} 用正则表达式把所有请求中的/student替换为空字符串再进行转发
ws: true, //默认为:true 是否支持webSocket
changeOrigin: false //默认为true 控制是否对请求的浏览器撒谎,请求头中host值,true时如果要访问的浏览器端口为66,则撒谎为自己是同ip端口为66的请求,false时转发时如实回答自己是代理服务器
},
//可以配置多个
//匹配所有/xxx开头的请求进行转发
'/xxx': {
target: 'http://localhost:312',
ws: true,
changeOrigin: false
}
}
}
})
Ajax请求
axios.get("http://localhost:8080/student/getStudentsMsg").then(
response=>{
console.log("请求成功:",response.data)
},
error=>{
console.log("请求失败:",response.message)
}
)
SpringBoot与Vue分离开发的配置
SpringBoot运行到81端口,类加上@CrossOrigin,解决跨域。
vue.config.js配置成下面的代码
module.exports = defineConfig({
transpileDependencies: true,
devServer:{
open:true, // 是否在服务器启动后打开默认浏览器
host:'localhost', // Vue.js 应用的主机名
port:80, // Vue.js 应用的端口号
https:false, // 是否使用 HTTPS
proxy:{ // 配置跨域
// 当你的请求 URL 是 "/axios/..." 时,
// Vue.js 会将这个请求转发到 "81/axios/..."
'/axios':{
target:'http://localhost:81/', // 要转发到的目标服务器的地址
ws:true, // 是否代理 websockets
changeOrigin:false, // 是否改变原始主机头为目标 URL
}
}
}
})
axios请求
axios({
method: 'POST',
//主机地址要写本机的,后面的路径跟其他的一样
url: "http://localhost/axios/Teacher/test",
headers: {'Content-Type': 'application/json'},
data: JSON.stringify({teacherSecretKey: teacherSecretKey}),
}).then(res => {
console.log("收到的测试信息:" + res.data);
}).catch(error => {
console.error(error);
});
更多推荐
已为社区贡献5条内容
所有评论(0)