1.什么是跨域问题?
“跨域指的是:浏览器不能执行其他网站的脚本,从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域。
2.使用代理服务器解决跨域问题
代理服务器相当于一个中间商,连接二个端口号不同的服务器。代理服务器与本机的服务器的端口一致,但他却能代替本机与另一个服务器交互获取数据。
2.1 vue中开启代理服务器。
vue.config.js中,编写devServer,proxy中写入需要访问资源的服务器的地址
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave:false,
// 开启代理服务器(其端口号与本机相同)
devServer: {
proxy:'http://localhost:5000'
}
})
2.2 编写axios请求,在methods中定义一个方法获取
getStudents(){
axios.get('http://localhost:8080/students').then(
response=>{
this.data =response.data
//请求成功后的数据
console.log('请求成功!',response.data)
},
err=>{
console.log("请求失败了!",err.message)
}
)
}
2.3当本机public文件夹中含有students文件时,代理服务器会直接获取本机的public中的资源,未避免这一现象出现。我们对其就行修改。
增加一行路径,但是最后给资源服务器时,也要去掉‘/board’这一路径,不让会出现404
devServer: {
//(1) 当本地的public文件夹中没有与请求资源相同的文件时
// proxy:'http://localhost:5000'
// (2) 当本地的public文件夹中有与请求资源相同的文件时
// 当本地的public文件夹中没有与请求资源相同的文件时
proxy: {
'/board' : {
target:'http://localhost:5000',
// 此时需要消除,凡是以board开头的路径都为空
pathRewrite:{'^/board':''},
changeOrigin:true
}
}
axios请求,也要加上这路径。
getStudents(){
axios.get('http://localhost:8083/board/students').then(
response=>{
this.data =response.data
console.log('请求成功!',response.data)
},
err=>{
console.log("请求失败了!",err.message)
}
)
}