springboot+vue 前后端分离的跨域问题

使用Postman测试接口完美通过,但是在前段使用axios访问的时候老是报‘Access-Control-Allow-Origin’错误。

解决方法如下:

在vue项目中config/index.js文件中找到proxyTable: {}

在里面添加如下代码:

proxyTable: {
  '/api': {
    target: 'http://localhost:8080/',//这个就是你访问的接口的地址
    changeOrigin: true,//开启请求头为target
    pathRewrite: {
      '^/api': 'http://localhost:8080/'  //这个主要是为了之后写axios的url时更简单
    }
  }
},

在写axios时就可以这样写:

this.axios.post('api/login',params).then(res=>{  
    console.log(res)
    var res=res.data
    if(res.success){
        this.$Message.success('Success!');
        this.$router.push("/index")
    }
    else{
        this.$Message.error('Fail!');
    }
})

//这里的api/login中的api即上面配好的http://localhost:8080/ 路径,不需要你每次都写完整的路径,即http://localhost:8080/XXX

发布了16 篇原创文章 · 获赞 2 · 访问量 6995

猜你喜欢

转载自blog.csdn.net/qq_41307492/article/details/105120324