vue2处理跨域问题

文章讲述了如何在Vue项目中通过vue.config.js配置proxy解决访问SpringBootRestController中的服务时的跨域问题,涉及到webpack.dev.conf.js的配置迁移。
摘要由CSDN通过智能技术生成

vue中访问springboot中的RestController中的服务

vue.config.js不生效-CSDN博客

1、创建项目

使用vue init webpack my_frontend 创建vue项目

 

在HelloWorld.vue文件中添加内容:

HelloWorld.vue 文件内容:

<template>

  <div>
    <el-table :data="tableData"  border style="width: 100%">
      <el-table-column prop="id"  label="ID" width="180"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="180"> </el-table-column>
      <el-table-column  prop="pwd" label="密码"> </el-table-column>
    </el-table>
  </div>
</template>


<script>

// import testApi from '../api/test.js'
import axios from "axios";
export default {
  name: 'HelloWorld',
  data () {
    return {
      tableData: [],
    }
  },
  mounted() {
    this.fetch();
  },
  methods:{
     fetch() {
        const http = axios.create({
          // baseURL: BASEURL,
          timeout: 1000 * 30,
          withCredentials: true,
          headers: { 'Content-Type': 'application/json; charset=utf-8'  }
        })
        http.get('/api/datas/v1/users').then((res) =>{
          this.tableData = res.data
           console.log(res)
        })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

2、在项目根目录下创建vue.config.js,并添加内容

module.exports = {

  devServer: {
    host: '127.0.0.1',
    port: 8080, //vue项目端口
    open: true,// vue项目启动时自动打开浏览器
    proxy: {
      '/api': { // '/api'是代理标识,用于告诉node,url前面是/api的就是使用代理的
        target: "http://127.0.0.1:8088", //目标地址,一般是指后台服务器地址
        changeOrigin: true, //是否跨域
        pathRewrite: { // pathRewrite 的作用是把实际Request Url中的'/api'用""代替
          '^/api': ""
        }
      }
    }
  }
}

但是运行项目访问,还是显示跨域问题, 访问restfull接口: '/api/datas/v1/users

没有替换为:http://127.0.0.1:8088/datas/v1/users,而是使用vue项目的访问url:

http://127.0.0.1:8080/api/datas/v1/users,可见vue.config.js没有作用。

3、查找原因

查看项目目录下package.json, package.json命令启动类的js 

打开/build/webpack.dev.conf.js, 显示内容如下:

注意到这个代理的关键配置是在这个config目录下,所以把这个vue.config.js中的proxy部份内容放到config目录下的index.js中的dev.proxyTable中就行了,不是官网上的放到根目录

4、重启项目测试

npm run dev

可以正常访问restful服务。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值