Home Web Front-end JS Tutorial axios handles http sending Post and get

axios handles http sending Post and get

Apr 17, 2018 pm 03:47 PM
axios http post

This time I will bring you axios processing http sending Post and get, axios processing http sending Post and get What are the precautions, the following is a practical case, let's take a look.

axios Chinese documentation # 

##

https://github.com/mzabriskie/axios#using-applicationx-www-form-urlencoded-format axios documentation

In terms of processing http requests, it is no longer recommended to use vue-

resource. Instead, use the latest axios. Here is a brief introduction.

Install

Use node

npm install axios
Copy after login
Use cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy after login

Basic usageMethod

get request

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
// Optionally the request above could also be done as
axios.get('/user', {
  params: {
   ID: 12345
  }
 })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
Copy after login

Post request

 axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
 })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
Copy after login
Execute multiple requests at the same time

function getUserAccount() {
 return axios.get('/user/12345');
}
function getUserPermissions() {
 return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
 .then(axios.spread(function (acct, perms) {
  // Both requests are now complete
 }));
Copy after login
The usage method of this is actually the same as the native ajax, and you can understand it at a glance.

Use application/x-www-urlencoded form of post request:

var qs = require('qs');
 axios.post('/bbg/goods/get_goods_list_wechat', qs.stringify({"data": JSON.stringify({
  "isSingle": 1,
  "sbid": 13729792,
  "catalog3": 45908012,
  "offset": 0,
  "pageSize": 25
 })}), {
  headers: {
   "BBG-Key": "ab9ef204-3253-49d4-b229-3cc2383480a6",
  }
 })
 .then(function (response) {
  // if (response.data.code == 626) {
   console.log(response);
  // }
 }).catch(function (error) {
  console.log(error);
 });
Copy after login
Specific usage reference document: https://github.com/mzabriskie/axios#using-applicationx-www-form-urlencoded-format

Note: For post requests, generally, the first parameter is the URL, the second parameter is the request body data to be sent, and the third parameter is the configuration of the request.

In addition: axios defaults to application/json format. If qs.stringify is not applicable, the final content-type format will still be json even if the request header is added.

For post requests, we can also use the following jquery ajax to implement:

    $.ajax({
     url:'api/bbg/goods/get_goods_list_wechat',
     data:{
      'data': JSON.stringify({
            "isSingle": 1,
            "sbid": 13729792,
            "catalog3": 45908012,
            "offset": 0,
            "pageSize": 25
          })    
     },  
     beforeSend: function(request) {
      request.setRequestHeader("BBG-Key", "ab9ef204-3253-49d4-b229-3cc2383480a6");
     }, 
     type:'post', 
     dataType:'json', 
     success:function(data){   
      console.log(data);
     },
     error: function (error) {
      console.log(err);
     },
     complete: function () {
     }
    });
Copy after login
Obviously, through comparison, it can be found that jquery's request form is simpler, and jqury's default data format is application/x-www-urlencoded, which is more convenient in this regard.

In addition, for two identical requests, even if both requests are successful, the results obtained by the two requests are different

It is not difficult to see: the results returned by using axios will be packed with one more layer than the structure (actual results) returned by jquery's ajax, including related config, headers, request, etc.

For get requests, I personally recommend using axios.get(), as shown below:

 axios.get('/bbg/shop/get_classify', {
  params: {
   sid: 13729792
  },
  headers: {
   "BBG-Key": "ab9ef204-3253-49d4-b229-3cc2383480a6"
  }
 })
 .then(function (response) {
  if (response.data.code == 130) {
   items = response.data.data;
   store.commit('update', items);
   console.log(items);
  }
  console.log(response.data.code);
 }).catch(function (error) {
  console.log(error);
  console.log(this);
 });
Copy after login
That is, the first parameter is: url, and the second parameter is a configuration object. We can set params in the configuration object to pass parameters.

I personally understand why get does not have a second parameter as the passed query

string , while post has a second parameter as the post data.

Because get can have no query string or get request, but post must have post data, otherwise there is no need to use post.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Display progress bar when JS uploads files

Layer front-end component image display function

The above is the detailed content of axios handles http sending Post and get. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does http status code 520 mean? What does http status code 520 mean? Oct 13, 2023 pm 03:11 PM

HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

What is http status code 403? What is http status code 403? Oct 07, 2023 pm 02:04 PM

HTTP status code 403 means that the server rejected the client's request. The solution to http status code 403 is: 1. Check the authentication credentials. If the server requires authentication, ensure that the correct credentials are provided; 2. Check the IP address restrictions. If the server has restricted the IP address, ensure that the client's IP address is restricted. Whitelisted or not blacklisted; 3. Check the file permission settings. If the 403 status code is related to the permission settings of the file or directory, ensure that the client has sufficient permissions to access these files or directories, etc.

http request 415 error solution http request 415 error solution Nov 14, 2023 am 10:49 AM

Solution: 1. Check the Content-Type in the request header; 2. Check the data format in the request body; 3. Use the appropriate encoding format; 4. Use the appropriate request method; 5. Check the server-side support.

Common network communication and security problems and solutions in C# Common network communication and security problems and solutions in C# Oct 09, 2023 pm 09:21 PM

Common network communication and security problems and solutions in C# In today's Internet era, network communication has become an indispensable part of software development. In C#, we usually encounter some network communication problems, such as data transmission security, network connection stability, etc. This article will discuss in detail common network communication and security issues in C# and provide corresponding solutions and code examples. 1. Network communication problems Network connection interruption: During the network communication process, the network connection may be interrupted, which may cause

How to implement HTTP streaming using C++? How to implement HTTP streaming using C++? May 31, 2024 am 11:06 AM

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

What status code is returned for an HTTP request timeout? What status code is returned for an HTTP request timeout? Feb 18, 2024 pm 01:58 PM

The HTTP request times out, and the server often returns the 504GatewayTimeout status code. This status code indicates that when the server executes a request, it still fails to obtain the resources required for the request or complete the processing of the request after a period of time. It is a status code of the 5xx series, which indicates that the server has encountered a temporary problem or overload, resulting in the inability to correctly handle the client's request. In the HTTP protocol, various status codes have specific meanings and uses, and the 504 status code is used to indicate request timeout issues. in customer

See all articles