vue项目中配置跨域


前言

前后端分离时,因为浏览器的同源策略,常常会遇到跨域问题,解决方式有:1.jsonp(get) 2.后端的crossorign 3.前端代理服务器,这里我仅介绍vue项目的常用解决方式


1.引入axios

a.dos窗口下载依赖

npm install axios --g

b.main.js中引入依赖全局注册

import axios from ‘axios’
Vue.prototype.$axios = axios

c.在vue页面中发送axios请求

export default {
    created(){
        this.$axios.post('/vue/auth/', 
        {
            "username":"roger"
        })
        .then(res => {
            console.log(res)
        })
        .catch(err =>{
            console.log(err);
        });  
    },
    data(){

    },
    methods:{

    }
}
</script>

2.配置跨域

a.config下的index.js配置

找到module.exports.dev中的proxyTable,配置如下:

// 跨域的代理中转服务器服务
    proxyTable: {
      // '/vue'会拦截axios请求中带有/vue的请求,例如:this.$axios.post('/vue/auth/')这种就会被拦截
      "/vue":{                                 // /vue代理target
        target: 'http://localhost:8081/',      // 后端接口的根目录
        // secure: true,                       // 如果是 https ,需要开启这个选项
        changeOrigin: true,                    // 是否跨域
        pathRewrite: {                         // 是否重写路径,看代理前端路径是否与后端路径一致
            '^/vue': '/java'                   
            // '^/vue': '/java'---> localhost:8080/vue/auth/ 通过代理服务器访问 localhost:8081/java/auth/
            // '^/vue': ''     ---> localhost:8080/vue/auth/ 通过代理服务器访问 localhost:8081/auth/
        }
      }
    },

pathRewrite方式1: ‘^/vue’: ‘/java’
在这里插入图片描述
axios请求 /vue/auth/–>http://localhost:8080/vue/auth/
在这里插入图片描述
后端的api地址

pathRewrite方式2: ‘^/vue’: ‘’
在这里插入图片描述
axios请求 /vue/auth/–>http://localhost:8080/vue/auth/
在这里插入图片描述
在这里插入图片描述

b.npm run dev重启

总结

上面的配置只是方便大家理解,建议写法如下:

    // 跨域的代理中转服务器服务
    proxyTable: {
      // '/api'会拦截axios请求中带有/api的请求
      "/api":{                                 
        target: 'http://localhost:8081/',      // 后端接口的根目录
        // secure: true,                       // 如果是 https ,需要开启这个选项
        changeOrigin: true,                    // 是否跨域
        pathRewrite: {                         // 重写路径
            '^/api': '' 
            // '^/api': '/api' ---> localhost:8080/api/auth/ 通过代理服务器访问 localhost:8081/api/auth/
            // '^/api': ''     ---> localhost:8080/api/auth/ 通过代理服务器访问 localhost:8081/auth/
        }
      }
    },

版权声明:本文为weixin_47729434原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。