In-depth understanding of Axios put requests: usage tips and best practices

In front-end development, we often need to interact with back-end servers. Among them, the PUT  request is a commonly used method for sending requests to update or modify data to the server. By sending a PUT request, we can update the status of the resource on the server.

image.png

Axios is a popular JavaScript library for   making  HTTP  requests in the browser and Node.js. It provides a simple and easy-to-use API, making it very convenient to send PUT requests. In this article, we will explore how to use Axios' PUT request and introduce different ways of writing parameters.

How to use Axios PUT request

The prerequisite for using Axios is that Axios is installed in the project. If you haven't installed it yet, you can install it with the following command:

npm install axios 或 yarn add axios

Next, we can introduce and use Axios in the code to make PUT requests.

First, in your  JavaScript  file, include Axios using:

import axios from 'axios';

Then, we can send the PUT request through the Axios  put method. Here is the basic usage:

axios.put(url, data, config) .then(response => { // 请求成功后的处理 }) .catch(error => { // 请求失败后的处理 });
  • url: The server-side address to which the PUT request is to be sent.
  • data: The data to be sent, usually a JavaScript object, will be converted into  JSON  format and sent to the server.
  • config: Optional parameters used to set request configurations, such as request headers.

Commonly used writing methods for passing parameters

Next, we will introduce several common ways of passing parameters.

1. Pass parameters in the URL

Parameters can be spliced ​​directly into the URL, which is the most common method of passing parameters:

const userId = 123; const newData = { name: 'John Doe', age: 30 }; axios.put(`/api/users/${userId}`, newData) .then(response => { // 请求成功后的处理 }) .catch(error => { // 请求失败后的处理 });

In the above example, we will  userId directly splice it at the end of the URL and  newData send it to the server as the request body.

2. Use URL parameters

params URL parameters can be passed using the parameters provided by Axios  :

const userId = 123; const newName = 'John Doe'; axios.put('/api/users', null, { params: { id: userId, name: newName } }) .then(response => { // 请求成功后的处理 }) .catch(error => { // 请求失败后的处理 });

In the above example, we pass the parameter as an object  params, and Axios will concatenate it behind the URL.

3. Use the request body to pass parameters

In addition to the above two methods, we can also pass data as the request body:

const userData = { id: 123, name: 'John Doe', age: 30 }; axios.put('/api/users', userData) .then(response => { // 请求成功后的处理 }) .catch(error => { // 请求失败后的处理 });

In this way, we directly pass the parameter object  userData as the second parameter to  put the method.

Practical cases

Now, let's learn more about how to use Axios' PUT request through a practical case.

1.Install json-server

First, you need to install json-server using npm or yarn in the project directory.

npm install -g json-server

Then, create a JSON file in the project directory to simulate your data. Assuming that the data you want to simulate is user data, you can create a  users.json file named and define the user data in it. users.json Example of file content:

{ "users": [ { "id": 1, "name": "Alice", "age": 25 }, { "id": 2, "name": "Bob", "age": 30 } ] }

Finally, run the following command in the terminal to start the json-server and specify the simulation data file:

json-server --watch users.json --port 3000

This will start a simulation server and listen on port 3000, using  users.json the data in the file as the simulated resource, as shown in the figure:

2.Send put request

The routes provided by the json-server above can be:

  • PUT  http://localhost:3000/users/:userId  First, create a new JavaScript file in the IDE editor (for example, putUser.js), then paste the following code and  node putUser.jsrun it on the console with the command.
const axios = require('axios'); const userId = 2; // 要修改的用户 id const updatedData = { name: 'Updated Name', age: 35 }; axios.put(`http://localhost:3000/users/${userId}`, updatedData) .then(response => { console.log('User updated:', response.data); }) .catch(error => { console.error('Error updating user:', error); });

Note: If an error is reported, please make sure it is installed  axios. The installation command isnpm install axios

This script uses Axios to send a PUT request to  http://localhost:3000/users/:id the address updating user information with ID 2 to  { name: 'Updated Name', age: 35 }.

 Debugging the backend interface using  Apifox

Apifox = Postman + Swagger + Mock + JMeter, Apifox supports debugging interfaces of http(s), WebSocket, Socket, gRPC, Dubbo  and other protocols, and integrates  the IDEA plug-in . When the back-end personnel finish writing the service interface, Apifox can be used to verify the correctness of the interface during the testing phase. The graphical interface greatly facilitates the efficiency of the project's launch.

In the example of this article, the interface can be tested through Apifox. After creating a new project, select "Debug Mode" in the project   , fill in the request address, and then quickly send the request and obtain the response result. The above practical case is shown in the figure:

Tips, Tricks and Considerations (continued)

  • Use the appropriate parameter passing method to send the PUT request. Choose the appropriate method according to your needs, splice it in the URL, use  params parameters, or pass the data as the request body.
  • For more complex requests, you can use Axios  config parameters to set request headers, authentication information, etc.
  • In practice,   ensure that the correct parameters and data format are passed depending on the specifics of the backend API .
  • Use Promise's  .then() and  .catch() methods to handle the success and failure of requests, as well as corresponding data processing.
  • It is recommended to add error handling to the request  .catch() to prevent unhandled exceptions.
  • When processing a request, you can perform different processing based on the status code returned by the server, such as handling different error conditions or successful responses.
  • Use developer tools, such as Chrome's Developer Tools, to monitor network requests and responses to help debug and troubleshoot issues.

Summarize

Axios is a powerful JavaScript HTTP client library that facilitates PUT requests to update resource status on the server. params We can implement different parameter passing methods by splicing URLs, using  parameters, or passing data as the request body. In practice, it is necessary to select the appropriate parameter transmission method according to the requirements of the back-end API, and perform corresponding processing according to the returned status code.

Knowledge expansion:

Reference links:

  1. Axios official documentation: Request Config | Axios Docs
  2. Express official website: Express - Node.js web application framework
  3. Chrome Developer Tools: https://developers.google.com/web/tools/chrome-devtools

Guess you like

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