API文档:https://cli.vuejs.org/zh/config/#devserver-proxy
安装以及基本使用
安装
npm i axios
导入
import axios from "axios"
方式一
methods: {
getStudent() {
axios.get("http://localhost:5000/students").then(
(response) => {
console.log("请求成功", response.data);
},
(error) => {
console.log("请求失败", error.message);
}
);
},
}
这里服务器端口号是5000,本地是8080,如果直接运行就会报错,因为跨域了。

跨域的时候需要借助代理服务器,1.nginx;2.vue-cli
这里用vue-cli学习成本低点
只需要在vue.config.js中粘贴相应的代码即可
module.exports = {
devServer: {
//注意:这里的端口号不是代理服务器的端口号,而是想发送请求给那个服务器的端口号,这里服务器端口号为5000
//代理服务器的端口号与本机端口号一致,都为8080.
proxy: 'http://localhost:5000'
}
}
App中的请求应该发给代理服务器,因此应该是8080端口
methods: {
getStudent() {
axios.get("http://localhost:8080/students").then(
(response) => {
console.log("请求成功", response.data);
},
(error) => {
console.log("请求失败", error.message);
}
);
},
},
然后需要重新启动ctrl+c

这样就请求成功了
注意:public为代理服务器的根路径,如果里面的文件对应了请求的数据,那么直接将public内的该文件内的数据返回,不会请求,并且这种方法只能配置一个代理服务器。
方式二
方式二相对来说比较麻烦,但是可以解决方式一的问题。
配置有所改变
devServer: {
proxy: {
//名字可以自定义
'/peiqi1': {
target: 'http://localhost:5000',
//这里的pathRewrite需要设置,请求过去的/peiqi1替换成空,不然就变成去找服务器中的peiqi1中的students或者cars了。
pathRewrite: { '/peiqi1': '' },
//ws是为了支持websocket用的
ws: true,
//changeOrigin是表示请求来源是否为原端口号,如果为true,则不告知真实端口号,告知的为请求的服务器的端口号。如8080->5000,这时候服务器上显示的来源为5000,而不是8080.如果为false则为真实端口号
changeOrigin: true
},
'/peiqi2': {
target: 'http://localhost:5001',
pathRewrite: { '/peiqi2': '' },
}
}
}
methods: {
getStudent() {
//这里需要穿插配置中设置的peiqi1
axios.get("http://localhost:8080/peiqi1/students").then(
(response) => {
console.log("请求成功", response.data);
},
(error) => {
console.log("请求失败", error.message);
}
);
},
getCar() {
axios.get("http://localhost:8080/peiqi2/cars").then(
(response) => {
console.log("请求成功", response.data);
},
(error) => {
console.log("请求失败", error.message);
}
);
},
},

拓展–vue-resource
在Vue1.0时候用的多,现在一般用axios,在配置后将axios改为this.$http即可,其他都一样。VM和VC都有这个$http
配置:
import Vue from 'vue'
import App from './App.vue'
//导入
import VueResource from 'vue-resource'
Vue.config.productionTip = false
//使用了use
Vue.use(VueResource)
new Vue({
render: h => h(App),
beforeCreate() {
// 在Vue的原型对象上添加个$bus
Vue.prototype.$bus = this
}
}).$mount('#app')
vc中
methods: {
searchInfo() {
this.$bus.$emit("getInfo", {
isFirst: false,
isLoading: true,
errorMsg: "",
users: [],
});
//axios改为了this.$http
this.$http
.get(`https://api.github.com/search/users?q=${this.textMessage}`)
.then(
(response) => {
console.log("收到数据了", response.data.items);
this.$bus.$emit("getInfo", {
isLoading: false,
errorMsg: "",
users: response.data.items,
});
},
(error) => {
this.$bus.$emit("getInfo", {
isLoading: false,
errorMsg: error.message,
users: [],
});
}
);
},
},
实现的效果跟axios一样。
2033

被折叠的 条评论
为什么被折叠?



