uniapp解决跨域问题以及uni.request的封装
在使用uniapp做小程序的时候发现了跨域问题以及uni.request的封装问题,于是写下此篇博客以便后续使用。
·
前言:
在使用uniapp做小程序的时候发现了跨域问题以及uni.request的封装问题,于是写下此篇博客以便后续使用
uniapp解决跨域问题
第一种方法
在manifest.json中的视图源码添加
"h5": {
"devServer": {
"port" : 8080, //浏览器运行端口
"https": false,
"proxy": {
"/api": {//修改配置跨域代理路由(需要重启)
"target": "http://localhost:9000",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/baseUrlTest": ""
}
},
"/baseUrlBuild": {
"target": "http://zhbz-test.xxx.com",
"changeOrigin": true,
"secure": false,
"pathRewrite": {
"^/baseUrlBuild": "" //路径重写,将接口路径中以/api开头的部分替换掉
}
}
}
}
},
使用:
uni.request({
url: 'http://localhost:8080/api/userInfo/login', //仅为示例,并非真实接口地址。
data: {
phone: 'this.phone',
pwd: 'this.pwd'
},
method:'POST',
// header: {
// 'custom-header': 'hello' //自定义请求头信息
// },
success: (res) => {
console.log(res.data);
this.text = 'request success';
}
});
第二种方法
在我写的另一篇文章中,链接:
https://blog.csdn.net/2201_75474092/article/details/130092433
uni.request的封装
在static内添加request.js和getData.js文件
request.js
let baseUrl = '/api/'; //域名或选取所有接口不变的那一部分
export const request = (options = {}) => {
//异步封装接口,使用Promise处理异步请求
return new Promise((resolve, reject) => {
// 发送请求
uni.request({
url: baseUrl + options.url || '', //接收请求的API
method: options.method || 'GET', //接收请求的方式,如果不传默认为GET
data: options.data || {}, //接收请求的data,不传默认为空
}).then(data => {
let [err, res] = data;
resolve(res);
//弹窗
uni.showToast({
title: '登录成功',
icon: 'none', //如果要纯文本,不要icon,将值设为'none'
duration: 2000 //持续时间为 2秒
})
}).catch(error => {
reject(error);
//弹窗
uni.showToast({
title: '请求失败',
icon: 'none', //如果要纯文本,不要icon,将值设为'none'
duration: 2000 //持续时间为 2秒
})
})
})
}
getData.js
import { request } from './request.js'; //导入封装好的js文件
//每一个请求的接口都返回一个函数,便于直接调用
//请求登录的接口
export const login = (data)=>{
return request({
url:'userInfo/login', //后端对应的接口,如果前端配置了跨域,这里直接写http://xx:xx后面的内容
method:'POST',//请求的方式,get,post等
data:data //请求所带的参数
})
}
//请求注册的接口
export const register = (data)=>{
return axios.request({
url:"",
method:'post',
data:data,
})
}
在登录页面中引入
import {login} from '../../static/getData.js'
在方法中使用
methods: {
async dengLu() {
await login(this.from).then(data => {
// console.log(data)
if( data.data.code == 200 ){
console.log(data.data)
uni.setStorage({
key: 'id', // 存储值的名称
data: data.data.data, // 将要存储的数据
success:res => {
// 成功后的回调
console.log(res);
}
});
uni.switchTab({
url:'/pages/home/home'
})
}
})
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)