Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to encapsulate the request interface in React project

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "how to encapsulate the request interface in the React project", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to encapsulate the request interface in the React project" can help you solve your doubts.

1. Include files:

We need to use these three files in our encapsulation process: Api.js, Apilp.js, and ApiURL.js.

The purpose of the 2.ApiIp.js file:

The function of the file is to call different interface request addresses in the development environment and production environment, the role of this file is to dynamically obtain the address in the browser for assembly, so that the address can be obtained dynamically. The code and comments are as follows:

/ / get the address in the current URL with the port number, return the current URL protocol without http://let projectAddrass = _ window.location.host;let projectAddrassNoPort = _ window.location.hostname;//, either http protocol or https protocol let protocol = _ document.location.protocol / / encapsulates the address of the request API. 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 request address of LOGO image export const logoImgAddress =` ${protocol} / / ${projectAddrassNoPort} `; / / the service address 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

The purpose of the 3.Api.js file:

This file is returned as a Promise object by requesting the entry file of the interface service, and then encapsulated again with the help of axios, because the two methods of then and catch in the Promise object allow us to facilitate further processing. The code comments are as follows:

Import axios from 'axios';import * as apiUrl from'. / ApiURL';import {notification} from 'antd';const key =' keepOnlyOne' / * * the method performed when the interface requests data * accepts the parameters as the requested path apiUrl, the request interface configuration parameter configObj * * @ param {String} apiUrl user incoming request path * @ param {Object} configObj user incoming interface parameter * / function getDataFromServer (apiUrl, configObj) {/ / the interface configuration parameter let {method = 'GET' passed in by the user Params = {}, data = {}, timeout = 5000} = configObj / * the returned Promise object contains then, catch methods * / 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: 'returned data format is incorrect'}); resolve (response) }} else {/ / handles a special case where 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) })})} / / Log in to export function loginClick (configObj) {return getDataFromServer (apiUrl.LOGIN, configObj);}

Other Dome files add this code:

Import {loginClick} from'. / Api';// uses let loginInfo = {method: 'POST',data: {account: username}} loginClick (loginInfo). Then ((response) = > {/ / do something}). Catch ((error) = > {/ / error something})

The purpose of the 4.ApiURL.js file:

Pass in the address through the ApiIp.js file, and then encapsulate a specific request path to assemble into a complete request address, and store the addresses of all the interface requests in a file, which can reduce the coupling and facilitate our maintenance. The code is as follows:

Import ApiIP from'. / ApiIp';// Log in export const LOGIN = `${ApiIP} / index/ captcha`. After reading this, the article "how to encapsulate request APIs in React Project" has been introduced. To master the knowledge points of this article, you still need to practice and use it. If you want to learn more about related articles, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report