如何使用Axios发送HTTP请求?详细分步指南

2021年11月28日06:34:51 发表评论 1,571 次浏览

Axios 是 Javascript 开发人员最喜欢的 HTTP 客户端之一。它用于从客户端和服务器端发送 HTTP 请求,尤其是 AJAX 请求。

在开发动态 Web 应用程序时,从 Javascript 端发送 HTTP 请求现在几乎是必需的。Axios 通过在 Javascript 的 XMLHttpRequest 接口上提供易于使用的抽象以及许多用户友好的功能和配置选项来简化此任务。

如何使用Axios发送HTTP请求?在本教程中,我们将通过代码示例和简化的解释来介绍你需要了解的有关使用 Axios 发送 HTTP 请求的所有信息。

让我们从这个问题开始我们的介绍。


为什么要选择 Axios?

要回答这个问题,让我们来看看可供开发人员使用的 Axios 替代方案。

Javascript 提供了一个内置接口XMLHttpRequest来处理 HTTP 请求。但是,用这个接口发送请求不是很直接,需要写太多行代码。

如果你使用过JQuery,那么你必须熟悉该$_ajax功能。它在 XMLHttpRequest 接口上提供了一个更简单、更易于使用的抽象,我们可以使用它以更少的代码行发送 HTTP 请求。但是随着像 JQuery 这样的库在过去几年变得过时,开发人员需要一个原生的 Javascript 解决方案来创建 HTTP 请求。

现在,Fetch API 和 Axios 是原生 Javascript 中用于发送这些请求的两种最流行的解决方案。然而,与 Fetch API 相比,Axios 具有优势,因为它为开发人员提供了一些独特的功能。在这里,我们列出了其中的一些。

  • 支持请求和响应拦截
  • 能够取消请求
  • 支持旧浏览器 (Internet Explorer 11)
  • JSON 数据的自动转换
  • XSRF 保护的客户端支持

由于其强大的功能集,开发人员现在开始更喜欢 Axios 而非 Fetch API 来发送 HTTP 请求。


安装 Axios

你可以在前端和后端安装和使用 Axios。如果你使用像 npm 这样的包管理器,则安装很简单。

npm install axios

如果你使用的是内容交付网络 (CDN),请将 Axios 脚本嵌入到 HTML 中。

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

或者,

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

Axios如何发送HTTP请求

使用 Axios 发送 HTTP 请求就像将包含所有配置选项和数据的对象传递给函数一样简单axios()

axios({
    method: "post",
    url: "/users",
    data: {
        username: "sam123",
        firstname: "sam",
        lastname: "smith"
    }
});

让我们仔细看看这里使用的配置选项。

  • method : 必须发送请求的 HTTP 方法
  • url : 请求必须发送到的服务器的 URL
  • data:在 POST、PUT 和 PATCH 请求的情况下,此选项提供的数据在 HTTP 请求的正文中发送。

要查看 Axios 请求函数可用的所有配置选项,请参阅其官方文档 。


专用请求功能

Axios发送HTTP请求代码示例:除了通用axios()功能之外,Axios 还提供了专用功能来简化发送不同类型的请求。以下是这些功能的列表。

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

例如,我们可以使用axios.post()函数来发送POST请求,而不是axios()通过将方法设置为“post”来使用函数。

axios.post("/users", {
    username: "sam123",
    firstname: "sam",
    lastname: "smith"
});

我们可以使用该axios.get()函数以类似的方式发送 GET 请求。

axios.get("/users", {
    params: {
        firstname: "sam"
    }
});

params 配置选项用于在 URL 中设置查询参数。

发送多个并发请求

Axios如何发送HTTP请求?我们可以使用 Axios 并发发送多个请求。为此,我们必须将一组请求调用传递给该Promise.all()函数。

Promise.all([
    axios.get("/users/sam123"),
    axios.get("/users/sam123/comments")
]);

使用 Axios 处理响应

如何使用Axios发送HTTP请求?当我们向远程服务器发送 HTTP 请求时,我们会收到来自该服务器的包含某些信息的响应。我们可以使用 Axios 检索此响应。

根据 Axios 文档,返回的响应包含以下信息。

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

由于 Axios 是基于 Promise 的,因此响应作为 Promise 返回。因此,我们需要使用then()catch()函数来检索响应并捕获错误(如果有)。

让我们看看如何处理 POST 请求返回的响应。

axios.post("/users", {
    username: "sam123",
    firstname: "sam",
    lastname: "smith"
    })
    .then(response => {
        console.log(response);
        console.log(response.data);
        console.log(response.data.userId);
        console.log(response.status);
        console.log(response.statusText);
    })
    .catch(error => {
            console.log(error.message);
    });

使用异步/等待

我们还可以使用 async/await 来发送 HTTP 请求并处理响应而不是承诺。

async function getUserData() {
    try {
        const response = await axios.get("/users/sam123");
        console.log(response);
    }
    catch (error) {
        console.log(error);
    }
}

处理并发请求的响应

在上一节中,我们使用了Promise.all()方法来发送多个并发请求。当传递给该方法的所有请求都完成时,它会返回一个带有每个请求的响应对象的承诺。我们可以使用传递给方法的数组中每个请求的索引来分隔响应。

Promise.all([
    axios.get("/users/sam123"),
    axios.get("/users/sam123/comments")
    ])
    .then(response => {
       const user = response[0].data
       const comments = response[1].data
    })
    .catch(error => {
        console.log(error);
    });

处理错误

Axios发送HTTP请求代码示例:如果使用 Axios 发送 HTTP 请求时发生错误,返回的错误对象包含特定信息,以帮助我们找出错误发生的确切位置。正如你将在以下示例中看到的,有三个地方可能会发生错误。

axios.post("/users", {
    username: "sam123",
    firstname: "sam",
    lastname: "smith"
    })
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        if (error.response) {
            //The response status is an error code
            console.log(error.response.status);
        }
        else if (error.request) {
            //Response not received though the request was sent
            console.log(error.request);
        }
        else {
            //An error occurred when setting up the request
            console.log(error.message);
        }
    });

通过 Axios 提供的这些信息,你可以根据错误发生的位置适当地处理错误。


使用 POST 请求发送数据

如何使用Axios发送HTTP请求?当使用 Axios 发送 POST 请求(还有 PUT 和 PATCH 请求)时,请注意我们如何将普通的 Javascript 对象作为数据传递。Axios 默认将此 Javascript 数据转换为 JSON。它还将“content-type”标头设置为“application/json”。

但是,如果你将序列化的 JSON 对象作为数据传递,Axios 会将内容类型视为“application/x-www-form-urlencoded”(表单编码的请求正文)。如果预期的内容类型是 JSON,则必须使用“headers”配置选项手动设置标头。

const data = JSON.stringify({name: "sam"});
const options = {
    headers: {"content-type": "application/json"}
}

axios.post("/users", data, options);

如果要发送除 JSON 之外的任何其他类型的数据,则必须显式转换数据并适当设置内容类型标头。Axios 提供了两个配置选项,transformRequesttransformResponse,你可以分别在发送请求和接收响应之前执行此转换。


转换数据

让我们看看在发送请求时如何使用这两个配置选项。

axios({
    method: "post",
    url: "users/sam123",
    data: {
        username: "sam123",
        firstname: "sam",
        lastname: "smith"
    },
    transformRequest: [(data, headers) => {
        //Transform request data as you prefer

        return data;
    }],
    transformResponse: [(data) => {
        //Transform the response data as you prefer

        return data;
    }]
});

为请求设置自定义标头

Axios发送HTTP请求代码示例:你可以轻松地为使用 Axios 发送的请求设置自定义标头。你只需将包含自定义标头的对象传递给你正在使用的请求方法。

const options = {
    headers: {"X-Custom-Header": "value"}
}

axios.get("users/sam123", options);

设置配置默认值

Axios如何发送HTTP请求?你可以设置默认配置选项,以便将它们应用于你使用 Axios 发送的每个请求。这样,你就不必重复设置所有请求通用的选项。

例如,如果要设置用于每个请求的基本 URL 或授权标头,则可以轻松实现,如下例所示。

axios.defaults.baseURL = "https://example.com";
axios.defaults.headers.common["Authorization"] = AUTH_TOKEN

设置实例的配置默认值

有时,由于我们发送的请求不同,为每个 HTTP 请求设置默认配置变得不切实际:我们可能会根据用户权限将请求发送到两个不同的 API 或使用不同的授权令牌。

在这种情况下,虽然我们无法找到对每个请求通用的配置选项,但我们可能能够找到对不同请求组通用的选项。Axios 为我们提供了一种为这些不同组分别设置默认配置的方法。

这是通过创建实例。

我们可以创建单独的实例并为每个实例设置默认配置。然后,我们可以使用这个实例对象代替 axios 对象发送请求。

//Create new instance
const instance = axios.create();

//Set config defaults for the instance
instance.defaults.baseURL = "https://example.com";
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;

//Send requests using the created instance
instance.get("/users", {
    params: {
        firstname: "sam"
    }
});

拦截请求

如何使用Axios发送HTTP请求?HTTP 请求拦截是 Axios 中最有趣的特性之一。它允许你拦截程序发送的请求和接收的请求,并在操作完成之前执行一些常见任务。此功能简化了与 HTTP 请求相关的后台任务的处理,例如日志记录、身份验证和授权。

为请求或响应定义拦截器是一项简单的任务。

axios.intercept.request.use(config => {
    //Intercept the request and do something before it is sent
    console.log("Request sent");
    return config;
}, error => {
    return Promise.reject(error);
});

axios.get("/users/sam123")
    .then(response => {
        console.log(response.data);
    });

在这里,配置对象是我们传递给 axios 函数或其别名之一的确切配置对象。因此拦截器可以完全访问请求配置及其数据。

设置请求拦截器后,程序每次发送新请求时,都会在控制台中记录“请求已发送”消息。

Axios发送HTTP请求代码示例:我们可以用类似的方式设置一个响应拦截器。

axios.intercept.response.use(config => {
    //Intercept the response and do something when it is received
    console.log("Response recieved");
    return config;
}, error => {
    return Promise.reject(error);
});

axios.get("/users/sam123")
    .then(response => {
        console.log(response.data);
    });

现在,每次收到响应时,都会将消息“收到响应”记录到控制台。

我们也可以为实例而不是 axios 对象定义拦截器。

instance.intercept.request.use(config => {
    //Intercept the request and do something before it is sent
    console.log("Request sent");
    return config;
}, error => {
    return Promise.reject(error);
});

取消请求

Axios如何发送HTTP请求?Axios 提供的另一个有趣的功能是能够随时取消请求。

在 Web 开发中,在某些情况下,我们可能会发现远程服务器对我们请求的响应不再重要。在这种情况下,我们可以通过简单地取消请求来节省系统资源。Axios 为我们提供了一种方法来做到这一点。

如果你想取消某个请求,它应该有一个在创建请求时创建的取消令牌。我们可以随时使用此令牌取消请求。

这就是取消过程的实现方式。

const cancelToken = axios.cancelToken;
const source = cancelToken.source();

axios.get("/users/sam123", {
    cancelToken: source.token  //create cancel token
    })
    .then(response => {
        console.log(response.data);
    })
    .catch(thrown => {
        if (axios.isCancel(thrown)) {
            console.log("Request cancelled", thrown.message);
        }
        else {
            //handle the error
        }
    })

//Cancel the request
source.cancel("Request cancelled by the user");

需要注意的是,我们可以使用单个源对象同时取消多个请求。调用 source.cancel 时,取消使用给定源创建取消令牌的所有请求。


防止 XSRF 攻击

跨站请求伪造 (XSRF) 是攻击者用来渗透 Web 应用程序并执行恶意任务的技术。在这些攻击中,攻击者伪装成受信任的用户并欺骗应用程序为他们的利益执行操作。

这可能会损害用户的隐私和安全,如果用户具有高级权限,甚至会导致攻击者获得对整个系统的访问权限。

Axios 通过在创建请求时嵌入额外的身份验证信息提供了一种防止此类攻击的方法。这就是它的实现方式。

const options = {
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
};

axios.post("/users", options);

概括

如何使用Axios发送HTTP请求?在本教程中,我们讨论了作为 Web 开发人员使用 Axios 发送 HTTP 请求需要了解的所有信息。如你所见,Axios 使处理 HTTP 请求和响应的任务变得异常简单。

它提供了许多配置选项来根据我们的需要改变默认行为。它提供了许多方法来简化发送 HTTP 请求的任务。在 Axios 的帮助下,你可以比你想象的更快地在应用程序的后端和前端实现 HTTP 请求发送功能。

因此,如果你还没有,请将 Axios 添加到你的 Javascript 库组中,并使用它轻松实现你的 HTTP 请求发送任务。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: