解决跨域的方法
跨域时浏览器能拿到数据,只是没有给到你
- 后端配置CROS(后端返回数据时带请求头使浏览器不认为是跨域)
- JSONP
- 代理服务器
- vue-cli提供的代理服务器
- 发送ajax请求先经过8080代理服务器,再去请求5000服务器
- 服务器直接不用ajax所有没有跨域
- 8080与代理服务器处于同协议域名端口,所有没有跨域
模拟跨域解决流程
- 开启服两台服务器 http://localhost:5000/和 http://localhost:5001/
- node启动 http://localhost:8080/往5000和50001请求数据
- 出现跨域问题,因为端口号不同
- 配置代理-获取数据
配置代理解决跨域
代理一般都是开发使用,生成环境不用方法一
在vue.config.js中添加如下配置:
devServer:{proxy:"http://localhost:5000"}
使用
//代理服务器默认会先去找你服务器有的的东西 所有下边两个会去找文件axios.get('http://localhost:8080/test.txt') //这样写会从文件夹中寻找test.txt文件axios.get('http://localhost:8080/students') //这样写会从文件夹中寻找students文件(不带后缀名)axios.get('http://localhost:8080/students') //获取5000students数据
说明:
- 优点:配置简单,请求资源时直接发给前端(8080)即可。
- 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
- 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)
方法二
webpack
编写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:5000changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080changeOrigin默认值为true*/
发送请求:
//http://localhost:8080 必须带 或者配置baseurlgetStudents(){axios.get('http://localhost:8080/api1/students').then(response => {console.log('请求成功了',response.data)},error => {console.log('请求失败了',error.message)})},getCars(){axios.get('http://localhost:8080/api2/cars').then(response => {console.log('请求成功了',response.data)},error => {console.log('请求失败了',error.message)})}
说明:
- 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
- 缺点:配置略微繁琐,请求资源时必须加前缀。
Vite
配置代理
在vite.config.js中添加如下配置: ```javascript //调用 //axios.defaults.baseURL = ‘/api’ //data = await $http({‘url’:’/one/data’});
import path from ‘path’ export default defineConfig({ server: { proxy: { ‘/api’: { target: ‘http://localhost:8888‘, //代理到目标地址 changeOrigin: true, //设置访问目标地址允许跨域 rewrite: (path) => path.replace(/^\/api/, ‘’), } } } })
<a name="eRKXN"></a>#### 环境变量代理一般都是开发使用,生成环境不用。在vite中`import.meta.env.DEV`环境变量跨域判断开发(true)或生产环境(false)> vite.config.ts 配置代理```jsonserver: {proxy: {// 正则表达式写法'^/A': {target: 'http://120.24.64.5:8088',changeOrigin: true,rewrite: (path) => path.replace(/^\/A/, '')},'^/B': {target: 'http://192.168.1.2',changeOrigin: true,rewrite: (path) => path.replace(/^\/B/, '')}}}
src/api/index.ts 编写接口
//利用环境变量设置不同环境下url信息
let preFn = function (prepath: string) {
return import.meta.env.DEV ? prepath : ''
};
//该接口匹配A同事解决跨域 并在生产环境中去除/A
export const adminLogin = () => request.post(preFn('/A')+'/admin/login')
//该接口匹配B同事解决跨域 并在生产环境中去除/B
export const adminInfo = ()=> request.get(preFn('/B')+'/admin/info')
如果env报错,tsconfig.json添加 "compilerOptions": {"types": ["vite/client"]} 具体看https://www.cnblogs.com/wisewrong/p/15971158.html
