ajax请求中,4种解决跨域问题的方法——自用笔记

272 篇文章 4 订阅
18 篇文章 0 订阅

在这里插入图片描述

1.配置类方式(实现WebMvcConfigurer)

2.使用@CrossOrigin注解

3.使用nginx反向代理解决跨域

4.Vue中配置代理服务器

方式一(案例1)

  • 配置vue.config.js
  • 注意5000代表请求后端的端口
module.exports = {
//开启代理服务器
	devServer: {
		proxy: 'http://localhost:5000',
	}
}

更改请求端口为本机端口

  • 8080表示前端端口,保持端口对应即可
    在这里插入图片描述

问题解决

重启服务器,重启脚手架

在这里插入图片描述

思维图

在这里插入图片描述

Vue代理缺点

  1. 不能控制是否需要代理
  2. 只能代理一个服务器

方式一(案例2)

我们请求一个http://localhost:9000/demo/user/list地址

  • 请求代码
      getUserList() {
        axios({
          method: 'get',
          url: 'http://localhost:8080/demo/user/list',
        })
            .then(res => {
              console.log(res)
              this.tableData = res.data
            })
  • vue.config.js代码
  devServer: {
    proxy: 'http://localhost:9000',
  },

方式二(案例1)

初始原始

	devServer: {
		proxy: {
			//请求前缀
			'api': {
				target: '',
				ws: true, //用于支持websocket
				changeOrigin: true, //用于控制请求头中的host值,默认是true
			},
			 '/foo': {
			 target: '<other_url>',
			 },
		},
	},

开启代理

	devServer: {
		proxy: {
			//请求前缀
			'/atguigu': {
				target: 'http://localhost:5000',

			},
		},
	},
  • 加上前缀

在这里插入图片描述

注意
  • 让目标服务器规避这个请求头
				pathRewrite: { '^/atguigu': '' },
	devServer: {
		proxy: {
			//请求前缀
			'/atguigu': {
				target: 'http://localhost:5000',
				pathRewrite: { '^/atguigu': '' },
			},
		},
	},

其他功能介绍

				ws: true, //用于支持websocket
				changeOrigin: true, //用于控制请求头中的host值,默认是true

开启多个代理

	devServer: {
		proxy: {
			//请求前缀
			'/atguigu': {
				target: 'http://localhost:5000',
				pathRewrite: { '^/atguigu': '' },
				ws: true, //用于支持websocket
				changeOrigin: true, //用于控制请求头中的host值,默认是true
			},
			// '/foo': {
			// target: '<other_url>',
			// },

			'/demo': {
				target: 'http://localhost:5001',
				pathRewrite: { '^/demo': '' },
				ws: true, //用于支持websocket
				changeOrigin: true, //用于控制请求头中的host值,默认是true
			},
		},
	},

方式二(案例2)

  • 依然是请求http://localhost:9000/demo/user/list
    getUserList() {
      axios({
        method: 'get',
        url: '/abc/demo/user/list',
      })
          .then(res => {
            console.log(res)
            this.tableData = res.data
          })
  //开启代理服务器
  devServer: {
    proxy: {
      '/abc': {
        target: 'http://localhost:9000',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/abc' : ''
        }
      }
    }
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鬼鬼骑士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值