跨域
浏览器的同源策略限制,域名不同的时候会出现跨域。
配置axios代理解决跨域
解决跨域问题思路:
由于服务器和服务器之间可以相互请求数据,是没有跨域的概念(如果服务器没有设置禁止跨域的权限问题)
我们可以配置一个代理的服务器可以请求另一个服务器中的数据,然后把请求出来的数据返回到我们的代理服务器中,代理服务器再返回数据给我们的客户端,这样我们就可以实现跨域访问数据。
axios请求
// main.js
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'
axios.get('/test')
.then(res => {
console.log(res)
})
.catch(err => {
console.error(err);
})
脚手架中的配置
在vue2.0中:修改config文件夹下的index.js文件,在proxyTable中加上如下代码:
proxyTable: {
'/api': {
target: 'http://localhost:8081/', //要解决跨域的接口的域名
secure:false, //如果是https接口,需要配置这个参数
changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
pathRewrite: {
'^/api': '' // 路径重写
}
},
},
在vue2.0中:vue-cli3 搭建完成后,项目目录中没有 vue.config.js 文件,需要手动创建,并配置以下信息
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:8081/',//接口的前缀
ws:true,//代理websocked
changeOrigin:true,//虚拟的站点需要更管origin
pathRewrite:{
'^/api':''//重写路径
}
}
}
}
}
vite 搭建完成后,在vite.config.js中,配置以下信息
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
'/api': {
target: 'http://localhost:8081/',
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, '')
}
}
}
})
小结
- 请求
/test,相当于请求:http://localhost:8080/api/test, - 创建的本地服务器的proxy会拦截
/api,并重写路径,将/api及以前替换为target的内容。实际请求的url是http://localhost:8081/test - 在浏览器的调试工具中,显示为
http://localhost:8080/api/test