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>