在项目中新建utils来保存封装发送请求功能的文件
其中request.js用来封装发送请求的功能函数
config.js用来封装发送请求的url地址
request.js
// 封装发请求方法
import config from './config'
export default(url,data={},method='GET')=>{
return new Promise((resolve,reject)=>{
// 执行异步任务
wx.request({
url:config.host+url,
data,
method,
success:(res)=>{
resolve(res.data)
},
fail:(err)=>{
reject(err)
}
})
})
}
config.js
// 和url相关的
export default {
host:'http://localhost:3001'
}
发送请求的时候,可能会存在跨域问题,在小程序中不存在这个问题,但是在h5的项目中可能会存在,所以需要配置代理服务器来解决这个问题
配置代理服务器(vue中,uniapp中也能使用)
在项目中新建vue.config.js文件,在里面配置代理
//配置代理服务器
module.exports = {
devServer: {
proxy: {
// /api是接头暗号,给devServer配置标识
'/api': {
target: 'http://localhost:3001', //代理地址
ws: true,
changeOrigin: true,
pathRewrite:{//路径重写
'^/api':''
},
//可配置多个代理服务器
'/foo': {
target: '<other_url>'
}
}
}
}
配置好代理服务器之后,在h5项目中启动时,请求的功能函数还需要做一些修改,主要就是请求的url地址,还有发送请求时需要携带/api
request.js中
index.vue中