Axios GET Requests: From Getting Started to Practice

Axios  is a very commonly used request library when making network requests . This article will introduce how to use axios to initiate a GET request, and list several ways of writing parameters in detail. At the same time, it will provide a practical case, which includes the process of basic routing and request processing, and ensures that it can run smoothly in the IDE editor.

What is axios' GET request?

Before we start, let's briefly understand what axios is and what a GET request is.

Introduction to Axios

Axios is a popular Promise-based  HTTP  client that can be used to make HTTP requests in browsers and Node.js environments. Its ease of use, powerful features, and extensive community support make it one of the preferred web request tools for front-end development.

GET request concept

A GET request is a method of requesting data from a server. When you need to get data from the server, you can use GET request. GET requests usually come with some parameters to specify the conditions of the request or filter the results.

Axios GET request parameter passing method

Next, we will introduce in detail how to use axios to make GET requests, and list several ways of writing parameters:

1. Basic GET request

Here is a basic GET request code example:

// 引入 axios const axios = require('axios'); // 发起 GET 请求 axios.get('https://api.example.com/data') .then(response => { // 请求成功处理 console.log(response.data); }) .catch(error => { // 请求失败处理 console.error(error); });

2. GET request with parameters (spliced ​​directly on the URL)

GET request parameters can be passed by concatenating parameters on the URL:

const axios = require('axios'); // 假设有两个参数:id 和 category const id = 123; const category = 'electronics'; // 使用模板字符串将参数拼接在 URL 上 axios.get(`https://api.example.com/data?id=${id}&category=${category}`) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });

3. GET request with parameters (using params object)

axios also provides  params object options for passing parameters in GET requests:

const axios = require('axios'); // 定义 params 对象 const params = { id: 123, category: 'electronics' }; // 将 params 对象传递给 GET 请求 axios.get('https://api.example.com/data', { params }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });

4. RESTful style GET request

If using a RESTful API, it is common to pass parameters directly as part of the URL:

const axios = require('axios'); // 假设需要获取 id 为 123 的商品信息 const productId = 123; // 使用 RESTful 风格传递参数 axios.get(`https://api.example.com/products/${productId}`) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });

Practice case

Mocking the server with Express.js

To demonstrate axios' GET request example, we will create a simple Node.js server and use the Express.js framework to process the request. Make sure you have axios and Express.js installed in your project before running.

First, create a file in the project directory  server.js and add the following code:

const express = require('express'); const app = express(); const port = 3000; app.get('/data', (req, res) => { // 假设这是一个模拟的数据 const data = { id: req.query.id, category: req.query.category, message: 'Data retrieved successfully!' }; res.json(data); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });

Next, start the server by running the following command in Terminal:

node server.js

Note: If an error is reported, please make sure whether it is installed  express, the installation command isnpm install express

Your server should now be  http://localhost:3000 running on and able to handle GET requests.

Finally, we will use axios on the client side to make a GET request. Create a file called in your project directory  client.js and add the following code:

const axios = require('axios'); // 假设有两个参数:id 和 category const id = 123; const category = 'electronics'; axios.get('<http://localhost:3000/data>', { params: { id, category } }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });

Run the following command in a terminal to run the client code:

node client.js

If all goes well, you should be able to see data fetched from the server in the console.

In addition, we have an easier method, we can use Apifox to simulate mock data, and then  client.js initiate a request in the file.

how to debug

API Mock is integrated in Apifox  , and we can simulate requests through " Cloud Mock"  .

First, enable Cloud Mock in the project, and there is a service URL under the "Enable button", which is the address to be requested later:

image.png

Then create a new interface, and   set the expected conditions and response data in the "Advanced Mock" :

Finally, client.jsafter the file rewrites the request path, just initiate the request:

Tips and Precautions

  • When using  axios.get() the method to initiate a GET request, if sensitive information (such as user credentials) is involved, it is recommended to use the HTTPS protocol to protect data security.
  • In actual development, it is recommended to extract configuration parameters such as server addresses and API endpoints into configuration files or environment variables for easy maintenance and deployment.

Summarize

This article introduces how to use axios to make GET requests, and shows four different methods of passing parameters. We also demonstrate how to use Express.js in the Node.js environment to create a simple server and interact with the client for data through a practical case.

Through this article, I hope readers can master how to use axios to initiate a GET request, and have an understanding of the method of passing parameters. Using axios, you can easily interact with the back-end server for data, bringing a better experience for front-end development.

Knowledge expansion:

reference link

Guess you like

Origin blog.csdn.net/m0_71808387/article/details/132058502