uni-app 封装发送请求,指定accept请求头(request.js)

说明

使用 uni.request() 发送请求

注意

报 404 错误时,仍然执行 success 方法

封装请求

在 src 目录下创建 utils 文件夹,然后创建 request.js 文件

代码如下:

// 将用户信息保存到本地的操作
import {setUid,getUid,setUsername,getUsername} from './userInfo'

// 开发模式的url,生产模式的url
const url_all = {
    // 'DEV': 'http://localhost:8082', // 开发
    'DEV': 'http://192.168.0.203:8082', // 开发
    'PRD': '/airship', // 生产环境。不能是 ./ ,因为前端路径会跟着改变
}

let BASEURL = url_all['DEV']


// 发起请求
function handleRequest(options, resolve, reject) {
    // console.log("request.js::",options.data)
    uni.showLoading({
        title: "加载中",
        mask: true
    });
    let opt = {
        url: BASEURL + options.url,
        method: options.method,
        header: {
            'accept':'application/json',  // 跨域时,accept请求头是 */*,导致后端无法判断ajax请求,所以指定
            // 'x-requested-with':'XMLHttpRequest', // 用于后端判断是否ajax请求,但通过accept请求头也可判断,所以不需要指定
            'uid':getUid(), // 携带用户id,用于后端判断是否登录超时
            'username':getUsername(), // 携带用户名
        },
        data: options.data,
        success: (response) => {
            // if (response.data.code === 3001) {
            //     logout()
            // }
            if (response.data.code !== 0) {
                uni.showToast({
                    icon: "none",
                    duration: 4000,
                    title: response.data.msg
                });
            }

            resolve(response.data)
        },
        fail: (fail) => {
            console.error("request.js fail:",fail);
            uni.showToast({
                icon: 'none',
                title: "发生错误或服务器没有响应,错误信息:"+fail.errMsg
            })
            // 放开下面代码,如果上层没有处理,页面报红
            // reject(fail); 
        },
        complete() {
            uni.hideLoading();
        }
    }
    if(options.header){
        // console.log("options.header:",options.header)
        // opt.data
        for(let key in options.header){
            opt.header[key] = options.header[key]
        }
    }
    uni.request(opt)
}

/**
 * request方法,可以传递更多数据
 */
export const request =(options={})=>{
    return new Promise((resolve,rejects)=>{
        handleRequest(options,resolve,rejects)
    })
}

/**
 * post 请求
 * 数据以json格式发送到服务器
 */
export const post =(url,data)=>{
    return new Promise((resolve,rejects)=>{
        handleRequest(
            {
                url,
                data,
                method:'POST',
            },
            resolve,
            rejects
        )
    })
}

/**
 * get请求
 * 请求头 content-type 的值是 application/x-www-form-urlencoded
 */
export const get =(url,data)=>{
    return new Promise((resolve,rejects)=>{
        handleRequest(
            {
                url,
                data,
                method:'GET',
                header: {
                    // 指定 get 请求,不发送json格式数据
                    'content-type' : "application/x-www-form-urlencoded",
                }
            },
            resolve,
            rejects
        )
    })
}

读写用户信息

https://www.malaoshi.top/show_1IX72O7noaP6.html

发请求

在 src 目录下创建 api 文件夹,然后创建 note.js 文件

import {request,get,post} from '@/utils/request.js';

export const getNoteByTid =(tid)=>{
    return get('/note/showById',
        {
            id:tid
        }
    )
}

export const saveNoteTitle =(title, content, typeId)=>{
    return post('/note/save',
        {
            title, 
            content, 
            typeId
        }

调用

在 .vue 文件中引入 note.js 文件,并调用相应方法

import {getNoteByTid} from '@/api/note.js'
saveNoteTitle(this.formData.title, this.formData.content, this.typeId)