赞
踩
1、例如:在api文件夹中新建一个api.js
- // 公共的方法
-
- const baseUrl = "http://192.xxx.xx.xx:8889"; // 请求地址
- const $ajax = {
- get: function({
- url,
- param,
- header
- }) {
- return new Promise(function(resolve, reject) {
- uni.request({
- url: baseUrl + url,
- data: param,
- method: "GET",
- success: function(res) {
- if (res.statusCode !== 200) {
- reject(res);
- } else {
- resolve(res);
- }
- },
- fail: function(err) {
- reject(err);
- }
- })
- })
- },
- post: function({
- url,
- data,
- header
- }) {
- return new Promise(function(resolve, reject) {
- uni.request({
- url: baseUrl + url,
- data: data,
- method: "POST",
- header: {
- 'Content-Type': 'application/x-www-form-urlencoded'
- },
- success: function(res) {
- if (res.statusCode !== 200) {
- reject(res)
- } else {
- resolve(res);
- }
- },
- fail: function(err) {
- reject(err)
- }
- })
- })
- },
- postJSON: function({
- url,
- data,
- header
- }) {
- return new Promise(function(resolve, reject) {
- uni.request({
- url: baseUrl + url,
- data: data,
- method: "POST",
- header: {
- 'Content-Type': 'application/json;charset=UTF-8'
- },
- success: function(res) {
- if (res.statusCode !== 200) {
- reject(res)
- } else {
- resolve(res);
- }
- },
- fail: function(err) {
- reject(err)
- }
- })
- })
- },
- upImg: function({
- url,
- imgUrl
- }) {
- return new Promise(function(resolve, reject) {
- uni.uploadFile({
- url: "baseUrl" + url,
- filePath: imgUrl,
- name: 'file',
- success: function(uploadFileRes) {
- resolve(uploadFileRes);
- },
-
- fail: function(err) {
- reject(err)
- }
- });
- })
- }
- }
- export default $ajax;
2、引入
例如:在main.js中全局引入
- // 在main.js中引入
-
- import ajax from './api/api.js'
3、使用
- // get请求
-
- this.$ajax.get({
- url: `/wx/wxLogin`,
- param: {
- password: this.pwd,
- username: this.name,
- uuid: this.uuid
- }
- }).then((res) => {
- console.log(res.data)
-
- })
4、携带token
有的接口在发送http请求的时候需要验证token,登陆成功后我们需要把Authorization字段的值放到header里面,携带token去发送请求。
①在api文件夹中新建config.js文件,封装一下方法
- const app = {
- apiUrl: 'http://192.xxx.xx.xxx:8889', //请求的地址
- baseRequest(obj) {
- try {
- const userToken = uni.getStorageSync('userToken');
- if (userToken) {
- if (obj.header) {
- obj.header["Authorization"] = userToken;
- } else {
- obj.header = {
- "Authorization": userToken
- };
- }
- obj.url = this.apiUrl + obj.url;
- uni.request(obj)
- } else {
- console.log("获取不到userToken")
-
- }
- } catch (e) {
- console.log(e)
- console.log("获取不到userToken")
- }
- },
- }
- export default app
②登陆成功后设置缓存
- // 设置缓存
-
- uni.setStorageSync('userToken', res.data.token),
③其他地方调用
- // 顺便介绍一下获取缓存
-
- getToken() {
- uni.getStorage({
- key: 'userToken',
- success: (res) => {
- // console.log('这是获取key中的内容',res)
- this.tokenData = res.data;
- console.log('这是获取token', this.tokenData)
- if (this.tokenData) {
-
- }
-
- }
- })
- },
-
- // 注意要引入config.js
-
- import app from "@../../api/config.js"
-
- // 在methods中调用封装好的方法
-
- getMaintenance() {
- app.baseRequest({
- url: `/repairType/xxx/xxx`,
- method: 'get',
- success: (res) => {
-
- }
- })
- },
5. 请求代码优化(新增请求日志和响应日志)
①
- // interface.js
-
- const baseUrl = "https://xxxxxxxxxxx";
-
- export default {
- config: {
- baseUrl: baseUrl,
- header: {
- 'Content-Type':'application/json;charset=UTF-8',
- 'x-requested-with':"XMLHttpRequest"
- },
- data: {},
- method: "GET"|| "POST",
- dataType: "json", /* 如设为json,会对返回的数据做一次 JSON.parse */
- responseType: "text",
- success() {},
- fail() {},
- complete() {}
- },
- interceptor: {
- request: null,
- response: null
- },
- request(options) {
- /* console.log('options11')
- console.log(options) */
- if (!options) {
- options = {}
- }
- options.baseUrl = options.baseUrl || this.config.baseUrl
- options.dataType = options.dataType || this.config.dataType
- options.url = options.baseUrl + options.url
- options.data = options.data || {}
- options.method = options.method || this.config.method
- if(options.header){
- options.header['Content-Type'] = options.header['Content-Type']|| this.config.header['Content-Type']
- }
- return new Promise((resolve, reject) => {
- let _config = null
-
- options.complete = (response) => {
- let statusCode = response.statusCode
- response.config = _config
- if (process.env.NODE_ENV === 'development') {
- if (statusCode === 200) {
- /* console.log("【" + _config.requestId + "】 结果:" + JSON.stringify(response.data)) */
- }
- }
- if (this.interceptor.response) {
- let newResponse = this.interceptor.response(response)
- if (newResponse) {
- response = newResponse
- }
- }
- // 统一的响应日志记录
- _reslog(response)
- if (statusCode === 200) { //成功
- resolve(response);
- } else {
- reject(response)
- }
- }
-
- _config = Object.assign({}, this.config, options)
- _config.requestId = new Date().getTime()
-
- if (this.interceptor.request) {
- this.interceptor.request(_config)
- }
-
- // 统一的请求日志记录
- _reqlog(_config)
-
- if (process.env.NODE_ENV === 'development') {
- // console.log(_config)
- // console.log("【" + _config.requestId + "】 地址:" + _config.url)
- if (_config.data) {
- // console.log("【" + _config.requestId + "】 参数:" + JSON.stringify(_config.data))
- }
- }
-
- uni.request(_config);
- });
- },
- get(url, data, options) {
- if (!options) {
- options = {}
- }
- options.url = url
- options.data = data
- options.method = 'GET'
- return this.request(options)
- },
- post(url, data, options) {
- if (!options) {
- options = {}
- }
- options.url = url
- options.data = data
- options.method = 'POST'
- return this.request(options)
- },
- put(url, data, options) {
- if (!options) {
- options = {}
- }
- options.url = url
- options.data = data
- options.method = 'PUT'
- return this.request(options)
- },
- delete(url, data, options) {
- if (!options) {
- options = {}
- }
- options.url = url
- options.data = data
- options.method = 'DELETE'
- return this.request(options)
- }
- }
-
-
- /**
- * 请求接口日志记录
- */
- function _reqlog(req) {
- if (process.env.NODE_ENV === 'development') {
- console.log("【" + req.requestId + "】 地址:" + req.url)
- if (req.data) {
- console.log("【" + req.requestId + "】 请求参数:" + JSON.stringify(req.data))
- }
- }
-
- }
-
- /**
- * 响应接口日志记录
- */
- function _reslog(res) {
- let _statusCode = res.statusCode;
- if (process.env.NODE_ENV === 'development') {
- console.log("【" + res.config.requestId + "】 地址:" + res.config.url)
- if (res.config.data) {
- console.log("【" + res.config.requestId + "】 请求参数:" + JSON.stringify(res.config.data))
- }
- console.log("【" + res.config.requestId + "】 响应结果:" + JSON.stringify(res))
- }
- switch(_statusCode){
- case 200:
- break;
- case 401:
- break;
- case 404:
- break;
- default:
- break;
- }
- }
-
②
- // index.js
-
- import http from './interface'
- export const execute = (data = {}) => {
- if (data.url != 'logon') {
- //设置请求前拦截器
- http.interceptor.request = (config) => {
- let token = uni.getStorageSync('accessToken')
- delete config.header['Authorization']
- if (token) {
- config.header['Authorization'] = token
- }
- }
- //设置请求结束后拦截器
- http.interceptor.response = async (response) => {
- const statusCode = response.statusCode;
- if (response.header.authorization) {
- uni.setStorageSync('accessToken', response.header.authorization)
- }
- if (statusCode === 401) {
- uni.showToast({
- title: '登录已失效,请重新登录',
- icon: 'none',
- duration: 2000
- })
- setTimeout(() => {
- uni.navigateTo({
- url: "../../pages/login/login"
- });
- uni.removeStorageSync('accessToken');
- }, 2000)
- }
- return response;
- }
- return http.request(data)
- } else {
- return http.request(data)
- }
-
- }
- const interfaces = {
- }
- export default {
- execute,interfaces
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。