vue-d2admin-axios asynchronous requests to access the first compare Jquery ajax, Axios, Fetch difference

Let me talk about the contrast it

I see Jquery ajax, Axios, Fetch the difference

 

introduction

Front-end technology is really a development of the field of fast, my entry time three years ago, only native XHR and Jquery ajax, we have been JQuery 1.9 version of the following does not support large file requests this issue cards for a long time (last I wrote a native XHR request). A blink of an eye, JQuery ajax had not ahead of us, axios and fetch have begun to seize the "request" the front-end highlands respectively. This article will attempt to set forth the differences between them, and give some of their own understanding.

1 JQuery ajax

$.ajax({
   type: 'POST',
   url: url,
   data: data,
   dataType: dataType,
   success: function () {}, error: function () {} });

This I do not have to say anything else, is a native XHR package, in addition also adds support for the JSONP. There is one that one is to say, JQuery ajax after years of maintenance updates, really have to be very convenient, advantage goes without saying; If you insist cite a few shortcomings, it may be

  • Itself is programmed for the MVC, does not meet the current wave of front-end MVVM
  • Based on the development of native XHR, XHR architecture itself is not clear, have an alternative to fetch the
  • JQuery entire project is too large, simply have to use the introduction of the entire JQuery ajax very unreasonable (take personalized packaging solutions can not enjoy the CDN service)

Although JQuery for front-end development work that we have had (and now also still have) a profound impact, but we can see that with the improvement of VUE, the rise of a new generation of REACT framework, as well as ES standard, the API update more, this JQuery kinds of large and JS libraries, the future road will become narrower and narrower.

Summary: Get the lead out, and can still rice, but rice is not always moving day.

2 Axios

axios({
    method: 'post',
    url: '/user/12345',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }
})
.then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });

After Vue2.0, especially the rain the river is recommended that you replace JQuery ajax with axios, presumably so that Axios has entered many people's eyes. Axios also on the nature of the native XHR package, but it is implemented version of Promise, in line with the latest ES specification from its official website you can see it were the following features:

  • Create a http request from node.js
  • Support Promise API
  • Client support to prevent CSRF
  • Provides interfaces concurrent requests (an important, convenient for a lot of operations)

The support to prevent CSRF actually quite good fun, is how to do it, is to make your every request with a get from the cookie key, depending on the browser same-origin policy, you can not get the fake site is cookie It was the key, so that you can easily identify the background to this request is misleading user input on the fake website in order to take the right strategy.

Axios provides both concurrent package, nor fetch the problems will be mentioned below, and the volume is small, the most worthy manner now be selected request.

Summary: Who dares Hengdao immediately, only my general Axios!

3 Fetch

fetch known as AJAX alternatives, and its benefits in the " traditional Ajax is dead, Fetch eternal life " is mentioned in the following points:

  • In line with separation of concerns, no input, output, and status tracking of events mixed in one object in
  • Better and more convenient writing, such as:
try {
  let response = await fetch(url);
  let data = response.json();
  console.log(data); } catch(e) { console.log("Oops, error", e); }

Frankly, the above reason for me absolutely nothing convincing, because whether or Jquery Axios have helped us put xhr package is good enough, it is also easy enough to use, why should we spend great efforts to learn fetch?

I think the dominance of the fetch is:

  • More bottom, rich API provided (request, response)
  • Out of the XHR, ES is the norm in the implementation of the new

Everyone loves new things, and frankly, as a front-end engineer, when I use the native XHR, although occasionally think to write ugly, but after using JQuery and axios, this one has been completely do not care. Of course, if the new fetch can do as good, I would choose to use fetch in order not to fall behind. This is in fact well understood: you have a fighter, magic changed N times, the performance reached the level of the F-10, but if someone gave you bring a new F-10, you will not hesitate to choose the new F-10-- is not only new, but also represents a potential change as well as new magic.

But recently, when I use fetch, but also encountered a lot of problems:

  • fetch is a low-level API, you can take it into consideration native XHR, it is not so comfortable to use, the need for packaging

E.g:

1) fetch request given only network, all of 400,500 as the request was successful, it is necessary to deal with the package
2) fetch is not the default band Cookie, you need to add the configuration item
3) fetch ABORT is not supported, are not supported timeout control, use setTimeout and timeout control achieved Promise.reject the request does not stop the process continues to run in the background, resulting in a waste flow
4) fetch no way to monitor the progress of native request, and can XHR

PS: fetch specific issues we can refer to: " fetch is not so beautiful as you think ," " frequently asked questions and solutions to use fetch "

See here, your heart must have a doubt, this is a damn thing uncompleted project Well, I still go back with Jquery or Axios forget - in fact, I was so intended. However, we must make is how I found the ability to fetch a xhr smaller than at the front end of the application: cross-domain process.

We all know that because the issue of same-origin policy, the browser's request is likely to casually cross-domain - must have a head or by means of cross-domain JSONP, however, fetch mode can be set to "no-cors" (no cross-domain) ,As follows:

fetch('/users.json', {
    method: 'post', 
    mode: 'no-cors',
    data: {}
}).then(function() { /* handle response */ });

After this we will get a return type is "opaque" is. It should be noted that this request is true after the arrival station, so we can use this approach to information reporting, before the image.src method more out of us a choice. In addition, we can see the network in the actual return after the request to set up cross-domain header background will help us advance debugging interface (of course, by chrome plugin we can do that). In short, fetch now is not very good, and I've tried a few fetch package package are not satisfactory.

Summary: The chief's children, need to grow up

to sum up

If you are pulled directly at the bottom of the article, you need to know about are not only brain to use axios, Jquery old clumsy, fetch the young innocent, only it justified its annual Axios!

  

++++++++++++++++++++++++++++++++++++++++++++++ I am a show dividing line ++++++++++++++++++++++++++++++++++++++++++++++ gas ++++++

 

Asynchronous request

D2Admin use  axios  an asynchronous request tool, and do some package.

axios address
Github https://github.com/axios/axios
asl https://www.npmjs.com/package/axios
Chinese documents https://www.kancloud.cn/yunye/axios/234845

# Introduction

Axios is based on the promise of a HTTP library, you can use the browser and node.js in.

  • Browser support and node.js
  • Support promise
  • To intercept the request and response
  • Energy conversion request and response data
  • You can cancel the request
  • Automatically convert JSON data
  • Browser support to prevent CSRF (cross-site request forgery)

# Browser Support

Chrome Firefox Safari Opera Edge IE
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ 11 ✔

Browser Matrix

Use

axios default usage will not be discussed here, we get data D2Admin recommended in your project using the following method:

# Interface addresses

Default request address d2-admin/.env

VUE_APP_API=/api/

The above settings during your visit to  /demo/a the actual time to visit /api/demo/a

# Distinguish between different environmental settings interface address

If you want different environments using different request address, you can  d2-admin/.env.development add settings (example) in which:

VUE_APP_API=/api-dev/

So you have a different public address request in a formal environment and development environment, the development environment to access  /demo/a real time access to /api-dev/demo/a

# -Class arrangement

Before you begin to use D2Admin develop your project, you should first modify the  d2-admin/src/plugin/axios/index.js settings under.

The default settings need to follow the following data returned formatting conventions:

{
  // 和后台约定的状态码
  code: 0, // 后台返回请求状态信息 msg: '返回信息', // data 内才是真正的返回数据 data: { list: [ ... ] } } 

After processing the data in response to the interceptor will return:

{
  list: [
    ...
  ] } 

# Business error

Example of data returned when an error occurs:

{
  // 和后台约定的状态码
  code: 'unlogin', // 后台返回请求状态信息 msg: '用户没有登录' } 

If the error for a specified processing method, should be added to the corresponding code in the response interceptor:

service.interceptors.response.use( response => { // 成功返回数据,在这里判断和后台约定的状态标识 } ) 

# HTTP error

If you need to specify the processing method for an http error code corresponding to the second parameter should be added in response to the interceptor.

service.interceptors.response.use( response => {}, error => { // 发生 http 错误,在这里判断状态码 } ) 

# No return code

In the default setting, if your interface does not return code field, will not be state (non-http status, but the background and the type of appointment to state) judgment, returned directly axios requested data returned.

For example, the interface returns the following data:

{
  list: [
    ...
  ] } 

In response to this interface interceptor determines not return code field, it will be returned directly to:

{
  list: [
    ...
  ] } 

# Design API

Suppose you have a return data API interface, to access it, you should at first  d2-admin/src/api create the appropriate file folder directory file, for example: d2-admin/src/api/demo/business/table/1/index.jsThis document should export one or more request:

import request from '@/plugin/axios'

export function BusinessTable1List (data) { return request({ url: '/demo/business/table/1', method: 'post', data }) } 

# Use the API to obtain data

API creates a file in the steps above, you should use in this page:

<script> import { BusinessTable1List } from '@/api/demo/business/table/1' export default { methods: { handleSubmit (form) { BusinessTable1List({ name: '' }) .then(res => { // 返回数据 }) .catch(err => { // 异常情况 }) } } } </script> 

Rather than directly in the page call axios.

TIP

Although not a mandatory requirement, please note that your API folder structure regularity

# Analog data

See  Plug | analog data

# Cross-domain issues

If your front-end and back-end interface to a cross-domain project occurs, you can configure the agent locally:

devServer: {
  proxy: {
    '/api': { target: 'http://47.100.186.132/your-path/api', ws: true, changeOrigin: true, pathRewrite: { '^/api': '' } } } } 

Result of the configuration request is  /api/login forwarded to the time  http://47.100.186.132/your-path/api/login. See more documents  Vue CLI 3 | devServer.proxy

 

Guess you like

Origin www.cnblogs.com/landv/p/11091450.html