1.具体的网络请求的工具的用法见node阶段视频
注意: egg后端的缓存,要求前端的网络请求运行携带缓存cookie数据,axios网络请求携带参数下面两种方式:
①axios.defaults.withCredentials=true;//让ajax携带cookie
②axios.post(url,{pwd:123},{ withCredentials: true },(res)=>{})
axios.get(url,{params:{pwd:123},{ withCredentials: true },(res)=>{})
后端egg中配置:
//设置允许哪些源可以跨域访问当前服务器
// credentials: true 跨域服务的页面去做cookie缓存
config.cors = {
origin: ' http://192.168.3.113:8080',
credentials: true//后端会给去前端返回缓存数据包 告诉浏览器 去做缓存
}
配置baseURL====>
main.js文件
import Vue from 'vue'
import App from './App.vue'
import axios from "axios"
axios.defaults.baseURL='http://localhost:8080/api1'; ====>要和地址栏中的访问index.html文件的路径一样
Vue.prototype.$axios=axios
new Vue({
render: h => h(App),
}).$mount('#app')
vue.config.js文件
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave:false,//关闭eslint的严格模式检测
devServer:{
port:"8080",
host:"localhost",
proxy:{
"/api1":{
target:"http://192.168.0.101:7001",
changeOrigin:true,
pathRewrite:{"^/api1":""}
}
}
}
})
使用:
mounted(){
this.$axios("/info").then((res)=>{
console.log(res)
})
}
2.网络请求工具的二次封装:
2.1 原理: 把用到的axios等网络请求工具封装成自己的工具
在项目中使用,防止axios出问题时,快速的更换工具 不会影响项目代码
2.2.设计:
xx.prototype.myaxios=axios
xx.myaxios.post=axios.post
xx.myaxios.get=axios.get
xx.myaxios.put=axios.put
举例:
main.js文件
import axios from "axios"
Vue.prototype.$axios=axios
tbox.vue文件
mounted(){
this.$axios("/api1/info").then((res)=>{
console.log(res)
})
vue.config.js文件
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave:false,//关闭eslint的严格模式检测
devServer:{
port:"8080",
host:"localhost",
proxy:{
"/api1":{
target:"http://192.168.0.103:7001",
changeOrigin:true,
pathRewrite:{"^/api1":""}
}
}
}
})
3.代理
tbox.vue文件
<template>
<div></div>
</template>
<script>
import axios from "axios"
export default {
data() {
return {
}
},
methods: {
},
mounted(){
axios("/api1/info").then((res)=>{
console.log(res.data)
})
}
}
</script>
vue.config.js文件
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave:false,//关闭eslint的严格模式检测
devServer:{
port:"8080",
host:"localhost",
proxy:{
"/api1":{
target:"http://192.168.0.103:7001",
changeOrigin:true,
pathRewrite:{"^/api1":""}
}
}
}
})