记录Vue proxy代理配置

本文主要介绍了在Vue CLI3项目中如何配置proxy代理,以解决开发环境下跨域问题。相较于Vue CLI2,配置位置从config/index.js的proxyTable转移到了vue.config.js文件中。详细配置步骤及示例代码提供了清晰的指导,帮助开发者顺利进行本地开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ps:此处配置是vue-cli3中!!!

proxy在vue-cli3项目中使用,在vue.config.js配置;

在cli2中使用的是proxyTable在config/index.js 里配置proxyTable内容

vue.config.js配置

module.exports = {
    devServer: {
        proxy: {
            '/lsh': {
                // 1.lsh这个值 的意义在于,声明axios中url已/lsh开头的请求都适用于该规则,最后的请求地址为http://192.168.1.117:8085/lsh/xxx/xxx
                // 2.告诉node,我接口只要是'/lsh'开头的才用代理
                // 注意是以/lsh开头,即:axios.post({url: '/lsh/xxx/xxx'})
                target: 'http://192.168.1.117:8085',
                // 此处target的意义在于:造成跨域是因为访问的host与我们的请求头里的origin不一致,所以我们要设置成一致,这个具体请看下文
                changeOrigin: true,
                pathRewrite: {'^/lsh': ''}
                // 比如,正确请求的路径为http://192.168.1.117:8085/adminLogin,但是代理之后请求的路径为http://192.168.1.117:8085/lsh/adminLogin,这里包含了lsh,所以需要在pathRewrite里面将lsh进行去除,所以设置了pathRewrite: {'^/lsh': ''}
                // 【'^lsh'】字符串其实是一个正则表达式,应该拆分成'^'和'lsh'两个字符串,其中'^'匹配的是字符串最开始的位置,也就是说,axios的请求URL写了'/lsh/adminLogin'的话,最后会在经过http-proxy-middleware的代理服务器时,会变成'/adminLogin',然后代理到http://192.168.1.117:8085这个服务器下面
                // 简而言之,pathRewrite的作用是一个替换的作用,在这里是将空的字符串替换所有的lsh
            }
        }
    }
}

APP.vue配置

<template>
    <div id="app">
        <input v-model="Name" type="text">
        <input v-model="Pwd" type="text">
        <button @click="handleLogin()">tijiao</button>
    </div>
</template>
<script>
import axios from 'axios'
export default {
    name: 'App',
    data() {
        return {
            Name: 'admin',
            Pwd: '111111'
        }
    },
    components: {},
    methods: {
        handleLogin() {
            console.log(this);
            axios.post('/lsh/adminLogin', {
                userName: 'admin',
                password: '123456'
            }).then(function(resp) {
                console.log(resp)
            }).catch(function(err) {
                console.log(err)
            })
        },
    }
}
</script>
<style>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>

学习地址:https://segmentfault.com/q/1010000012607105

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值