一、基于axios封装的request网络请求
1.1 HbuilderX创建项目
初始项目结构如下图:
1.2 安装axios
npm install --save axios@0.19.0
1.3 拷贝js_sdk文件夹到项目根路径下
百度网盘链接:链接:https://pan.baidu.com/s/1PvixwCqt-1eXgelRHUa0OQ
提取码:4hmv
–来自百度网盘超级会员V1的分享
1.4 项目根路径下创建utils文件夹
1.4.1 创建http.js
import axios from '@/js_sdk/gangdiedao-uni-axios'
// 创建自定义接口服务实例
const http = axios.create({
baseURL: 'http://127.0.0.1:8099',//根据个人后端情况,修改此处baseURL
timeout: 6000, // 不可超过 manifest.json 中配置 networkTimeout的超时时间
withCredentials: true,
headers: {
'Content-Type': 'application/json',
//'X-Requested-With': 'XMLHttpRequest',
},
})
// 拦截器 在请求之前拦截 添加token
http.interceptors.request.use(config => {
//请求前有关处理逻辑
return config
})
// 响应后的拦截
http.interceptors.response.use(response => {
//响应拦截处理逻辑
return response;
}, error => {
return Promise.reject(error.message)
})
export default http
1.4.2 基础使用
1.方式一:全局配置
main.js中,新增行4、行8代码
import Vue from 'vue'
import App from './App'
// 引入http.js
import http from './utils/http.js'
Vue.config.productionTip = false
//添加原型属性到Vue对象
Vue.prototype.$http = http;
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
使用:
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{name}}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
name: 'Hello'
}
},
onLoad() {
//页面加载时,调用服务端接口,获取类型,$http已在main.js中进行全局配置
var that = this
this.$http.get('/SysType/getById?id=1001')
.then(res => {
this.name = res.data.data.name
})
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
2.方式二:局部使用
在页面*.vue的
import http from '@/utils/http.js'
// get 请求
http.get(URL, [params]).then((res) => {
**
}).catch(error => {
**
}).finally(() => {
**
})
// post 请求
http.post(URL, [data]).then(res => {
}).catch(error => {
}).finally(() => {
})
1.5 项目链接
1.5.1前端
链接:https://pan.baidu.com/s/1GsJFWYlaGA5DzPdlfNVvoA
提取码:lbfs
–来自百度网盘超级会员V1的分享
1.5.2 服务端
链接:https://pan.baidu.com/s/1-Md9phpS5BFv5qa1djUqmg
提取码:i3dy
–来自百度网盘超级会员V1的分享
1.5.3 数据库脚本
链接:https://pan.baidu.com/s/1B3H1wxlMHsKYPtJEk_AIsw
提取码:mj7u
–来自百度网盘超级会员V1的分享