Js は現在のブラウザ デバイス タイプを取得します。カプセル化 get、post リクエスト Ts

1. ワンキースイッチのフロントエンドログ

let isPrintf = localStorage.getItem("printf");
export function printf(message?: string, ...optionalParams: any[]) {
    
    
    if (isPrintf) {
    
    
        console.log(message, ...optionalParams);
    }
}

2. 現在のブラウザのデバイス タイプを取得し、それが一般ユーザーに有効であることを確認します。

//获取当前设备的类型 0:PC  1:Mobile
export function getDeviceType() {
    
    
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    return flag ? 1 : 0;
}

3. フェッチに基づいたポストリクエスト

export async function post(url: string, query: Object) {
    
    
    return fetch(url, {
    
    
        method: "post",
        headers: {
    
    
            "Content-type": "application/json",
        },
        body: JSON.stringify(query),
    }).then((response) => response.json());
}

4.フェッチに基づくgetリクエスト

export async function get(url: string) {
    
    
    return fetch(url, {
    
    
        method: "get",
        headers: {
    
    
            "Content-type": "application/json",
        },
    }).then(response => response.json()).catch(err => err);
}

5. 時間をフォーマットし、day.js に依存する

import dayjs from "dayjs";
dayjs().format();
/**
 * 格式化时间
 * @param timestamp 
 * @param formatStr "ddd, MMM D, YYYY, h:mm:ss A"|'YYYY/MM/DD HH:mm:ss'
 */
export function formatTime(timestamp: number, formatStr: string) {
    
    
    if (timestamp.toString().length === 10) {
    
    
        timestamp = timestamp * 1000;
    }
    return dayjs(timestamp).format(formatStr);
}

おすすめ

転載: blog.csdn.net/kuilaurence/article/details/129403796