npm i axios
import axios from 'axios'
axios.get(url).then(
response => {
console.log('请求成功了',response.data)
},
error => {
console.log('请求失败了',error.message)
}
)
npm i vue-resource
//引入插件
import vueResource from 'vue-resource'
//使用插件
Vue.use(vueResource)
this.$http.get(url).then(
response => {
console.log('请求成功了')
},
error => {
console.log('请求失败了')
}
)
在vue.config.js中添加如下配置:
devServer:{
proxy:"http://localhost:5000"
}
说明:
编写vue.config.js配置具体代理规则:
module.exports = {
devServer: {
proxy: {
'/api1': {// 匹配所有以 '/api1'开头的请求路径
target: 'http://localhost:5000',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api1': ''}
},
'/api2': {// 匹配所有以 '/api2'开头的请求路径
target: 'http://localhost:5001',// 代理目标的基础路径
changeOrigin: true,
pathRewrite: {'^/api2': ''}
}
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000 (修改源地址为服务器地址)
changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080(保留请求地址)
changeOrigin默认值为true
*/
说明: