Elegant front-end ajax requests (the http client is axios) and ajaxaxios

Source: Internet
Author: User

Elegant front-end ajax requests (the http client is axios) and ajaxaxios

Preface

AJAX, Asynchronous JavaScript and XML (Asynchronous JavaScript and XML), a web development technical solution for creating interactive web applications.

Asynchronous JavaScript:

Use the [JavaScript language] and related [browser class library] functions to send requests to the server. After the server completes processing the requests, [automatically execute a JavaScript callback function ].

PS:The whole process of the above requests and responses is [secretly], and there is no perception on the page.

The following is not much to say. Let's take a look at the text of this article.

In this article, the http client is axios

Let's start with a story.

APIS like axios that support Promise are already friendly. After successful requests, we can get the data returned by the backend from the Response of then. For example:

axios.get('/user/12345') .then((response) => { console.log(response); }) .catch((error) => { console.log(error); });

Data is stored inresponse.dataThis means that each request needs to be processed once to obtain the actual data.

Then, in actual scenarios, the backend basically does not directly send data to us. It will encapsulate the data, suchresponse.dataThe structure of is as follows:

{ "date": "2017-12-14 15:21:38", "success": true, "obj": { ... }, "version": "V1.0"}

So,response.data.objThis is what we really want. Hello, so we need to process each request more.

One day, the backend said,"response.dataIt is no longer an object. It is changed to a JSON string. Let's take a look ~".

Then, yes, every interface is every, and we need to change itJSON.parse(response.data).objOh, half your life!

If the backend says, "I have changed back to the object. You can cancel the previous process ~"...

If the backend says, "Not all objects are objects, some of them are JSON strings. For details, refer to the updated interface documentation ~"...

If we never met each other...

Later we

ES6 Proxy is used to modify the default behavior of some operations. It is equivalent to making changes at the language level, so it is a kind of "meta programming", that is, programming language.

Proxy can be understood as setting up a "blocking" layer before the target object. The external access to this object must first intercept through this layer. Therefore, a mechanism is provided, attackers can filter and rewrite external accesses.

To relieve the above troubles, we need to encapsulate all interface requests in a unified manner. In this way, even if the backend is changed, we only need to modify one place or even not!

const apiService = new Proxy(axios, { get (target, propKey, receiver) { return function (...args) { return target[propKey](...args) .then((res) => {  const resData = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;  return typeof resData.obj === 'string' ? JSON.parse(resData.obj) : resData.obj; }) .catch((err) => {  throw err; }); } }});

The corresponding interface request is changed:

apiService.get('/user/12345') .then((data) => { console.log(data); }) .catch((error) => { console.log(error); });

"If you want to change it, I will lose it !"

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.