API
Axios 提供了多种请求方法,用于处理不同的 HTTP 请求类型。
-
axios.request()
:通用请求方法,支持自定义配置。
-
axios.get()
:发送 GET 请求。
-
axios.delete()
:发送 DELETE 请求。
-
axios.head()
:发送 HEAD 请求。
-
axios.options()
:发送 OPTIONS 请求。
-
axios.post()
:发送 POST 请求。
-
axios.put()
:发送 PUT 请求。
-
axios.patch()
:发送 PATCH 请求。
axios.request()
通用请求方法,支持自定义配置。
1const requestApi = () => {
2 axios.request({
3 method: "GET",
4 url: "http://127.0.0.1:3000/posts"
5 }).then((response) => {
6 console.log(response);
7 }).catch((error) => {
8 console.error("请求失败:", error);
9 });
10};
axios.get()
发送 GET
请求,用于获取资源。
1const getApi = () => {
2 axios.get("http://127.0.0.1:3000/posts").then((response) => {
3 console.log(response);
4 }).catch((error) => {
5 console.error("请求失败:", error);
6 });
7};
axios.delete()
发送 DELETE
请求,用于删除资源。
1const deleteApi = () => {
2 axios.delete("http://127.0.0.1:3000/posts/2").then((response) => {
3 console.log(response);
4 }).catch((error) => {
5 console.error("请求失败:", error);
6 });
7};
axios.head()
发送 HEAD
请求,用于检查资源是否存在,或者获取资源的元数据(如响应头信息)。
1const headApi = () => {
2 axios.head("http://127.0.0.1:3000/posts").then((response) => {
3 console.log("HEAD 请求成功,响应头信息:", response.headers);
4 }).catch((error) => {
5 console.error("HEAD 请求失败:", error);
6 });
7};
axios.options()
发送 OPTIONS
请求,用于获取目标资源所支持的通信选项。
它通常用于跨域请求(CORS)的预检请求,也可以用于获取资源支持的 HTTP 方法。
1const optionsApi = () => {
2 axios.options("http://127.0.0.1:3000/posts").then((response) => {
3 console.log("OPTIONS 请求成功,允许的 HTTP 方法:", response.headers["allow"]);
4 }).catch((error) => {
5 console.error("OPTIONS 请求失败:", error);
6 });
7};
axios.post()
发送 POST
请求,用于创建新资源。
1const postApi = () => {
2 axios.post("http://127.0.0.1:3000/posts", {
3 author: "dancy",
4 title: "学习 Axios"
5 }).then((response) => {
6 console.log(response);
7 }).catch((error) => {
8 console.error("请求失败:", error);
9 });
10};
axios.put()
发送 PUT
请求,用于更新资源。
1const putApi = () => {
2 axios.put("http://127.0.0.1:3000/posts/2", {
3 author: "dancy",
4 title: "学习 JavaScript"
5 }).then((response) => {
6 console.log(response);
7 }).catch((error) => {
8 console.error("请求失败:", error);
9 });
10};
axios.patch()
发送 PATCH
请求,用于部分更新资源。
1const patchApi = () => {
2 axios.patch("http://127.0.0.1:3000/posts/2", {
3 title: "更新标题"
4 }).then((response) => {
5 console.log(response);
6 }).catch((error) => {
7 console.error("请求失败:", error);
8 });
9};