解决vue的跨域问题

解决vue的跨域问题:

1.创建一个新的文件命名为vue.config.js

在这里插入图片描述

2.编写解决跨域问题代码,配置跨域

module.exports = {
    devServer: {
        proxy: {  //配置跨域
            '/api': {
                target: 'http://localhost:8081/',  //这里后台的地址模拟的;应该填写真实的后台接口
                changOrigin: true,  //允许跨域
                pathRewrite: {
                    /* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/core/getData/userInfo 时
                      实际上访问的地址是:http://121.121.67.254:8185/core/getData/userInfo,因为重写了 /api
                     */
                    '^/api': ''
                }
            },
        }
    }
}


在这里插入图片描述
和接口连接的代码:

 methods: {
    // getUser() {axios.get('http://localhost:8081/mybatis_plus/user/allUser').then(response => (this.tableData = response.data))}
    getUser() {axios.get('/mybatis_plus/user/allUser').then(response => (this.tableData = response.data))}
  },
  created() {
    this.getUser();
  }

3.main.js里面导入axios

import axios from 'axios'
import Axios from 'axios'

Vue.prototype.$axios = Axios
Vue.config.productionTip = false

//跨域关键代码
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'

测试一下:
在这里插入图片描述
由图可以知道,我们浏览器请求的地址是前端是url,但是后台请求是我们后台接口的地址,这就解决了跨域的问题。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值