服务器代理
实现原理
为了解决跨域问题,有几种实现的方式1.jsonp script标签有访问外部资源的功能(不常用) 2.cors(设置一些特殊的响应头) 3.vue脚手架,使用服务器的代理,vue脚手架自己创造一个代理服务器,代理服务器的地址和本地地址一样,然后本地向代理服务器访问,代理服务器向目标服务器访问,然而服务器之间是不存在同源策略
实现过程
一.配置:简单配置,在vue.config.js里面配置,直接写链接,只有写到端口号就可以了,不要写具体的
devServer: { proxy: 'http://localhost:8000' }
请求:一般使用axios进行网络的请求,请求的地址是本地的地址,但是请求的具体内容要加上
axios.get('http://localhost:8080/students').then(response=>{
console.log(response.data);
},error=>{
console.log(error.message);
});
缺点:1.不能配置多个代理,并且不能自己控制是否自己走代理
因为这样在访问的时候,如果访问到前端有一样的资源文件名就不会走代理
二.配置:复杂配置,要设置头信息,可以配置多个代理服务器,并且设置头信息,就可以知道这个就是要走代理的
devServer: {
proxy: {
// 配置两个代理服务器
'/api': {
target: 'http://localhost:8000',
// '/api'这个标志会加入这个代理服务器去访问的路径,会出错
// 重写路径,将/api替换为空字符串
pathRewrite:{'^/api':''},
// 是否启用websocket
ws: true,
// 是告诉别的服务器自己的地址,true就是不告诉
changeOrigin: true
},
'/demo': {
target: 'http://localhost:9000',
pathRewrite:{
'^/demo':'',
}
}
}
}
请求:
// 使用代理服务器,方式二,加入标志,放在端口号的后面,标志着不论如何都要走代理
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);
});