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,测试封装好的请求方法
请求接口: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>
此时小程序端已正常运行,h5页面产生了跨域,
因为我们后台的端口是localhost:7788,
客户端的地址:http://localhost:8080/#/pages/index/index
所以产生了跨域
小程序里不存在跨域,但是如果是H5的项目存在跨域:
根目录下创建 vue.config.js:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:7788',
ws: true,
changeOrigin: true,
pathRewirte:{ //路径重写
'^/api':''
}
},
'/foo':{
target:'http://localhost:3001'
}
}
}
}
修改发送请求:
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)
}
})
})
}
如果在h5中还是不行,
显示请求成功,但是数据是html样式的
"h5": {
"title": "Test",
"devServer": {
"port": 8082,
"disableHostCheck": true,
"proxy": {
"/api": {
"target": "http://localhost:7788",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/api": ""
}
}
}
}
}
这样h5获取到的数据就是正常的了