Axios

发布: (2026年1月15日 GMT+8 17:06)
2 min read
原文: Dev.to

Source: Dev.to

Cover image for Axios

Axios 方法

方法用途
axios.get()获取数据
axios.post()创建/提交数据
axios.put()完全更新资源
axios.patch()部分更新
axios.delete()删除数据

在项目中使用 Axios 的方式

步骤 1:安装 Axios

npm install axios
# or
yarn add axios

步骤 2:基本的 Axios 用法

import axios from 'axios';

// GET request
axios.get('http://localhost:3000/api/users')
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

// POST request
axios.post('http://localhost:3000/api/users', {
  name: 'John',
  email: 'john@example.com'
})
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

// PUT request (update)
axios.put('http://localhost:3000/api/users/1', {
  name: 'Jane'
})
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

// DELETE request
axios.delete('http://localhost:3000/api/users/1')
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

步骤 3:在 React 组件中使用(配合 Hooks)

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Fetch data on component mount
  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await axios.get('http://localhost:3000/api/users');
      setUsers(response.data.users);
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  if (loading) return 
Loading...
;

  if (error) return 
Error: {error}
;

  return (
    
      {users.map(user => (
        
          
### {user.name}

          
{user.email}

        
      ))}
    
  );
}

export default UserList;

步骤 4:带身份验证的请求(发送令牌)

axios.post('http://localhost:3000/api/auth/login', {
  email,
  password
}, {
  withCredentials: true, // Send cookies
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

步骤 5:创建可复用的 Axios 实例

创建 src/api/axiosInstance.js

import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: 'http://localhost:3000/api',
  withCredentials: true
});

// Add token to all requests
axiosInstance.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export default axiosInstance;

在组件中使用该实例:

import axiosInstance from '../api/axiosInstance';

// Instead of full URL
axiosInstance.post('/auth/login', { email, password })
  .then(response => console.log(response.data))
  .catch(error => console.log(error));
Back to Blog

相关文章

阅读更多 »