1,LanBowanShop/utils/request.js
import cofig from './config.js'
export default (url,data={},method='GET')=>{
return new Promise((resolve,reject)=>{
uni.request({
url:cofig.baseUrl+url,
data,
method,
success(res) {
resolve(res.data);
},
fail(err) {
reject(err);
}
})
})
}
2,LanBowanShop/utils/config.js:
export default {
baseUrl: 'http://localhost:7788'
}
3, Test the encapsulated request method
Request interface: http://localhost:7788/getIndexData
<script>
//1.导入封装好的请求数据方法
import http from '@/untils/request.js';
export default {
data() {
return {
title: 'Hello'
}
},
methods: {
//2.请求首页数据
async getIndexData() {
let {
data: res
} = await http('/getIndexData');
console.log(res);
}
},
created() {
// 3.在声明周期函数中使用
this.getIndexData()
}
}
</script>
At this time, the applet is running normally, and the h5 page generates a cross-domain,
Because our background port is localhost:7788,
Client address: http://localhost:8080/#/pages/index/index
So a cross-domain
There is no cross-domain in the applet, but if it is an H5 project, there is a cross-domain:
Create vue.config.js in the root directory:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:7788',
ws: true,
changeOrigin: true,
pathRewirte:{ //路径重写
'^/api':''
}
},
'/foo':{
target:'http://localhost:3001'
}
}
}
}
Modify send request:
page/index.vue
// 获取首页数据
methods: {
//2.请求首页数据
async getIndexData() {
// #ifdef MP-WEIXIN
let {data:res} = await http('/getIndexData'); //小程序
// #endif
// #ifdef H5
let {data:res} = await http('/api/getIndexData'); //h5
// #endif
console.log(res);
}
},
untils/request.js
import config from './config.js';
export default (url, data = {}, method = 'GET') => {
return new Promise((resolve, reject) => {
uni.request({
// #ifdef MP-WEIXIN
url: config.baseUrl + url, //小程序
// #endif
// #ifdef H5
url,
//#endif
data,
method,
success: (res) => {
resolve(res)
},
fail: (erro) => {
reject(erro)
}
})
})
}
If it still doesn't work in h5,
It shows that the request is successful, but the data is in html style
"h5": {
"title": "Test",
"devServer": {
"port": 8082,
"disableHostCheck": true,
"proxy": {
"/api": {
"target": "http://localhost:7788",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/api": ""
}
}
}
}
}
In this way, the data obtained by h5 is normal.