Personal Study Notes:
When sending a request, I don’t want to repeatedly write the interface address every time I send a request. The interface request uni.request() is too cumbersome.
1. Create api.js to encapsulate all request interface addresses
//baseurl
const baseurl = 'http://localhost:3000/api/'
//方法一
// class apiUrl{
// static urls(){
// let getAllCategory=`${baseurl}getAllCategory`
// return {
// getAllCategory,
// }
// }
// }
//方法二
let apiUrl = function() {
// 请求菜品分类
let getAllCategory = `${baseurl}getAllCategory`
return {
getAllCategory,
}
}
export {apiUrl}
2. Create request.js to encapsulate uni.request request
// Get 请求
let getRequest = function(urls) {
return new Promise((resolve, reject) => {
uni.request({
url: urls,
method: "GET",
success: (res) => {
resolve(res.data)
},
})
})
}
//发送Post请求
export { getRequest }
3. It can be introduced partially in the components that need to be introduced, or globally in the main.js file
(1) Introduced in main.js
// 全局url地址
import {apiUrl} from './api/api.js'
Vue.prototype.ApiUrl = apiUrl
//全局get请求
import {getRequest} from './api/request.js'
Vue.prototype.GetRequest=getRequest
use:
// 请求全部菜品分类
async getCatagory(){
// 接口地址
let url=this.ApiUrl().getAllCategory
console.log(url);
// 发送请求
let res=await this.GetRequest(url)
console.log(res);
}
result:
(2) Introduce where needed, locally
Import and use:
import {getRequest} from '../../api/request.js'
import {apiUrl} from '../../api/api.js'
export default{
data(){
return{
}
},
methods:{
// 请求全部菜品分类
async getCatagory(){
// 接口地址
let url=apiUrl().getAllCategory
console.log(url);
// 发送请求
let res=await getRequest(url)
console.log(res);
}
},
onLoad() {
// 请求全部菜品分类
this.getCatagory()
// 请求全部菜品信息
}
}
result: