Skip to content

js http request

fetch

javascript
async function PostRequestData(url: string, headers: any, data: any) {
    let resp: any = await fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json", ...headers
        },
        body: JSON.stringify(data)
    });
    let result_data = null;
    if (resp.status == 200) {
        result_data = JSON.parse(await resp.text())
    }
    return { status: resp.status, data: result_data }
}

axios

javascript
import axios, { AxiosRequestConfig, AxiosError } from 'axios';


async function RequestData(method: AxiosRequestConfig['method'], url: string, headers?: Record<string, string>, data?: any) {
    try {
        const response = await axios({
            method,
            url,
            headers: {
                'Content-Type': 'application/json',
                ...headers,
            },
            data,
            timeout: 10 * 60 * 1000,
        });

        return { status: response.status, data: response.data };
    } catch (error) {
        if (axios.isAxiosError(error)) {
            const axiosError = error as AxiosError;
            if (axiosError.response?.status === 401) {
                return { status: 401, data: null };
            }
        }
        return { status: 500, data: null };
    }
}

export default { RequestData };

Released under the MIT License.