zoukankan      html  css  js  c++  java
  • 微信小程序封装http请求

    const baseUrl = 'http://localhost:8768/';  //后续可以改为你自己的域名接口地址
    
    const request = (url, options) => {
        return new Promise((resolve, reject) => {
            wx.request({
                url: `${baseUrl}${url}`, //域名接口地址
                method: options.method, //配置method方法
                data: options.method === 'GET' ? options.data : JSON.stringify(options.data), //如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
                header: {
                    'Content-Type': '',
                    'Authorization': wx.getStorageSync('Login')?wx.getStorageSync('Login').token:''
                }, //header中可以添加token值等
                success(request) { //监听成功后的操作
                    if (request.statusCode === 200) {
                        resolve(request.data)
                    } else {
                        reject(request.data)
                    }
                    if (request.data.code === 401) {
                        wx.removeStorageSync('Login')//如果返回401,可以做一些操作
                    }
                },
                fail(error) { //返回失败也同样传入reject()方法
                    reject(error.data)
                }
            })
        })
    }
    
    //封装get方法
    const get = (url, options = {}) => {
        return request(url, {
            method: 'GET',
            data: options
        })
    }
    //封装post方法
    const post = (url, options) => {
        return request(url, {
            method: 'POST',
            data: options
        })
    }
    //封装put方法
    const put = (url, options) => {
        return request(url, {
            method: 'PUT',
            data: options
        })
    }
    //封装del方法
    const del = (url, options) => {
        return request(url, {
            method: 'DELETE',
            data: options
        })
    }
    
    module.exports = {
        get,
        post,
        put,
        del
    }

    然后在js或者vue代码里面引入

    import http from '@/config/httputils'

    调用get方法

    http.get('你的接口地址',{参数,如果没有就不用传}).then(res => {
             console.log(res) 
    })    
    

      

  • 相关阅读:
    为什么利用多个域名来存储网站资源会更有效?
    事件绑定和普通事件的区别
    浏览器地址栏输入一个URL后回车,将会发生的事情
    JS数据类型及数据转换
    JS中的NaN和isNaN
    大数据的结构和特征
    系统重装后,如何重新找回hexo+github搭建的博客
    javascript操作符
    html头部
    html中链接的使用方法及介绍
  • 原文地址:https://www.cnblogs.com/javagg/p/13749618.html
Copyright © 2011-2022 走看看