Encapsulates the files contained in the directory

  • Api.js

  • ApiIp.js

  • ApiURL.js 

           

The role of the apiip.js file

The function of this file is to call different interfaces to request addresses in the development environment and the production environment. In the production environment, the function of this file is to dynamically obtain the address in the browser for assembly, so that you can dynamically obtain the address without writing dead

// Get the address in the current URL, with the port number, without http://
let projectAddrass = window.location.host;
let projectAddrassNoPort = window.location.hostname;
// Returns the current URL protocol, either HTTP or HTTPS
let protocol = document.location.protocol;
// Encapsulate the address of the request interface. If there is a layer of project name in the server, you need to add it, for example: / ZZXL /
export const interfaceIp = `${protocol}//${projectAddrass}/zzxl`;
// The requested address of the LOGO image
export const logoImgAddress = `${protocol}//${projectAddrassNoPort}`;
// Address of the external service
export const publicIp = process.env.NODE_ENV === 'development' ? 'http://10.222.40.243:8088' :
interfaceIp;
export const logoImgIp = process.env.NODE_ENV === 'development' ? 'http://127.0.0.1' :
logoImgAddress;Copy the code

The role of the apiurl.js file

By introducing the address passed in by apiip.js and encapsulating the specific request path to assemble the complete request address, all the interface request addresses can be put into one file, reducing the coupling degree and facilitating maintenance.

import ApiIP from './ApiIp'; / / loginexport const LOGIN = `${ApiIP}/index/captcha`;Copy the code

The role of the api.js file

The entry file of the external request interface service, rewrapped by AXIOS, is returned as a Promise object, because the Promise object contains the then and catch methods for further processing.

import axios from 'axios';
import * as apiUrl from './ApiURL';
import {notification} from 'antd';
​
const key = 'keepOnlyOne'; ** @param {String} apiUrl specifies the request path * @param {Object} configObj The interface parameter */ passed by the userfunctionGetDataFromServer (apiUrl, configObj) {// Interface configuration parameters passed in by the userlet {
        method = 'GET', params = {}, data = {}, timeout = 5000 } = configObj; /** * The return Promise object containsthenCatch method */return new Promise(function (resolve, reject) {
        axios({
            url: apiUrl,
            method: method,
            params: params,
            data: data,
            timeout: timeout,
            headers: {
                'Content-Type': 'application/json'.'token': window.sessionStorage.getItem('token') | |' '
            }
        }).then(function (response) {
            if(response){
                if (response.data && response.data.code) {
                    resolve(response);
                }else {
                    notification.error({
                        key,
                        message: 'Operation failed',
                        description: 'Wrong format of data returned'}); resolve(response); }}else// Response returns nothing notification.error({key, message:'Operation failed',
                    description: 'Server error'
                });
                resolve(response);
            }
        }).catch(function (error) {
            notification.error({
                key,
                message: 'Operation failed',
                description: 'Network exception, please try again later'}); reject(error); })})} // Loginexport function loginClick(configObj) {
    return getDataFromServer(apiUrl.LOGIN, configObj);
}Copy the code

Dome used by other components

// Import {loginClick} from'.. /Api'; / / uselet loginInfo = {
method: 'POST',
data: {
account: username
}
}
loginClick(loginInfo).then((response) => {
// do something
}).catch((error)=>{
    // error something
})Copy the code

A special request interface

Post access to data, get streams, download files. Special treatment is required.

import axios from 'axios';
import {notification} from 'antd'; /** * Select some data in the export table * 1. ExportArray and downLoadURL are mandatory * 2. When downLoadFileName is null, download * 3 by default. * * @param {Array} * * @param {Array} * * @param {Array}export@param {String} downLoadFileName The name of the downloaded file * @param {String} downLoadURL the address of the service request * @param {String} _this this * @param {String} stateName The name of the named state */export function getStreamData(exportArray, downLoadFileName, downLoadURL, _this, stateName) {// Return if the Array passed is emptyif(! (exportArray.length > 0)) {
        notification.warn({
            message: 'Please select the data to export first',
            description: 'Unable to export without selecting data to export'
        });
        return;
    }
​
    axios({
        method: 'post',
        url:downLoadURL,
        data: JSON.stringify(exportArray),
        headers: {
            'Content-Type': 'application/json'.'token': window.sessionStorage.getItem('token') | |' '
        },
        responseType: 'blob'
    }).then((response) => {
        if(response){
            const blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8'}); // The name of the downloaded filelet filename = 'excel.xlsx';
            if(downLoadFileName) { filename = downLoadFileName; } // Use the Download attribute for non-Internet Explorerif('download' in document.createElement('a')) {let downloadElememt = document.createElement('a');
                let href = ' ';
                if(window.URL){
                    href = window.URL.createObjectURL(blob);
                }else {
                    href = window.webkitURL.createObjectURL(blob);
                }
                downloadElememt.href = href;
                downloadElememt.download = filename;
                document.body.appendChild(downloadElememt);
                downloadElememt.click();
                if(window.URL){
                    window.URL.revokeObjectURL(href);
                }else{ window.webkitURL.revokeObjectURL(href); } // Clear the selected data after successful exportif(_this && stateName) { _this.setState({ [stateName]: [] }); }}else{// Internet Explorer, download from Navigator, support Internet Explorer 10+if(navigator.msSaveblob) {// Clear selected data after successful exportif (_this && stateName) {
                        _this.setState({
                            [stateName]: []
                        });
                    }
                    returnnavigator.msSaveBlob(blob, filename); }}}else {
            notification.warn({
                message: 'Failed to export selected data',
                description: 'Failed to call interface to export selected data'
            });
        }
​
    }).catch(() => {
        notification.error({
            message: 'Operation failed',
            description: 'Network exception, please try again later'}); })}Copy the code