当前位置:   article > 正文

uniapp 封装request请求包含token信息_uniapp vue3封装请求携带token

uniapp vue3封装请求携带token

1.首先在根目录新建common/http目录,然后在http中新建两个js如 图

2.http.js代码

  1. import Vue from 'vue'
  2. const request = (params) => {
  3. // 显示加载数据的提示
  4. uni.showLoading({
  5. title: '加载中',
  6. mask: true
  7. })
  8. return new Promise(function(resolve, reject) {
  9. const baseUrl = Vue.prototype.$baseUrl;
  10. let token_value=store.state.token;
  11. uni.request({
  12. method: params.method,
  13. data: params.data,
  14. url:baseUrl + params.url,
  15. header: {
  16. 此处是token 可不加,如果加了需要配置后端允许跨域
  17. 'token': token_value
  18. },
  19. success(res) {
  20. setTimeout(function() {
  21. resolve(res)
  22. }, 500);
  23. },
  24. fail(err) {
  25. reject(err)
  26. },
  27. complete() {
  28. setTimeout(function() {
  29. uni.hideLoading()
  30. }, 500);
  31. }
  32. })
  33. })
  34. }
  35. export default request;

3.api.js 存放的是所有的接口

  1. import request from "./http.js"
  2. import Vue from 'vue'
  3. export default {
  4. //获取app版本
  5. api_getUpdateApp: function(params) {
  6. return request({
  7. method: "POST",
  8. url: "index/app_fun/getUpdateApp",
  9. data: params
  10. });
  11. },
  12. ///获取首页的功能列表
  13. api_getFunList:function(params) {
  14. return request({
  15. method:"POST",
  16. url:"api/app_fun/getFunList",
  17. data:params
  18. })
  19. },
  20. }

 3.配置main.js,允许全局使用

  1. import Vue from 'vue'
  2. import App from './App'
  3. import api from 'common/http/api.js'
  4. Vue.prototype.$api = api
  5. if (process.env.NODE_ENV === 'development') {
  6. //开发环境
  7. Vue.prototype.$http="http://192.168.0.103/"
  8. Vue.prototype.$baseUrl = "http://192.168.0.103/public/index.php/"
  9. Vue.prototype.$fileUrl = "http://192.168.0.103/public/"
  10. } else {
  11. //生产环境
  12. Vue.prototype.$http="https://s.june.com/"
  13. Vue.prototype.$baseUrl = "https://s.june.com/public/index.php/"
  14. Vue.prototype.$fileUrl = "https://s.june.com/public/" //图片展示域名
  15. }
  16. App.mpType = 'app'
  17. const app = new Vue({
  18. ...App
  19. })
  20. app.$mount()

4.页面中调用接口

  1. <template>
  2. <view class="content">
  3. </view>
  4. </template>
  5. <script>
  6. export default {
  7. data() {
  8. return {
  9. title: 'Hello',
  10. }
  11. },
  12. onLoad() {
  13. /* 该接口是在api.js中定义过的 */
  14. this.$api.api_getUpdateApp({
  15. user_id:'sdfsdfsd',
  16. name:'测试'
  17. }).then(res=>{
  18. /* 成功的回调 */
  19. }).catch(err=>{
  20. /* 失败回调 */
  21. }).finish(e=>{
  22. /* 成功或者失败都会执行 */
  23. })
  24. },
  25. methods: {
  26. }
  27. }
  28. </script>
  29. <style>
  30. </style>

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号