Encapsulating ajax requests

Encapsulation method (Promise encapsulates ajax)

Here, we use Promise of ES6 to encapsulate an ajax request. We can do some public operations, such as intercepting token and processing login verification

let request = ({type, url, data, headers, dataType, params, contentType, isBody, async}) => {//ES6 syntax
    let requestObj = {
        url: url,
        type: type
    if (headers) {
        requestObj['headers'] = headers;
    if (params) {
        requestObj['data'] = params;
    if (data) {
        requestObj['data'] = data
    if (dataType) {
        requestObj['dataType'] = dataType
    if (contentType) {
        requestObj['contentType'] = contentType
    if (isBody) {
        requestObj['contentType'] = 'application/json;charset=utf-8'
        requestObj['data'] = JSON.stringify(data)
    if (!async) {
        requestObj['async'] = async

    //Promise encapsulation
    return new Promise((resolve, reject) => {//This sentence is a routine, remember
            success: function (res) {
            error: function (jqXHR, textStatus, errorThrown) {
                reject(jqXHR, textStatus, errorThrown)

It can be seen that request is a function, and the parameter is an object, which contains some request parameters of ajax. It returns a Promise object wrapped with ajax request. In the parameter, when isBody is true, set contentType and convert data data into string. This is to simplify some steps when sending request when springboot parameter @ requestBody is used, When the springboot interface parameter is set to @ requestBody, the parameter: {isBody: true}

How to use

There is a basic in the top picture js file, in which we write the request. (it is recommended to put api requests into one or more js files)

function api_login(data) {
    return request({
        type: 'post',
        url: "/login",
        data: data

function api_getInfo() {
    return request({
        type: 'get',
        url: "/user/info"

The above defines two request requests, one is login, and the other is to obtain user information after successful login. They all return a Promise object.

Used in the project, the following is a user login

function login(){
	// ...... validate logon
	Send a request to the backend to verify the user name and password
	api_login(data).then(res => {
        if (res.errcode) {
        localStorage.setItem("accessToken", res.data.accessToken);
        localStorage.setItem("refreshToken", res.data.refreshToken)
        api_getInfo().then(res => {
            localStorage.setItem("user", JSON.stringify(res.data))
            window.location.href = "/"
    }).catch(error => {
        $("#loginErrMsg").text(" system exception, login failure ")

After we use the API to define the content before we log in, there is no error_ The login method makes a login request, res is the data returned by the background, saves the token and refreshToken locally, and obtains the user's personal information after logging in. A login verification is complete.


Look back. Let's first define a request js file is divided into two parts. One part defines an interceptor, captures 401403 and other requests, makes corresponding processing, and then defines a request function. The parameters are the ajax request parameter object we usually use, and returns a promise object, which contains ajax requests. Define a basic js file, which stores various interface methods that need to request the background. Each method defines url, type, etc. Finally, we can use it directly in our own js file. Because the return object is promise object, it can be passed then() is called chained.

Keywords: Javascript Ajax

Added by mike_revolution on Fri, 04 Mar 2022 00:21:36 +0200