基本使用

axios()

1axios({
2  // 请求类型
3  method: "",
4  // url
5  url: "",
6  // 请求体
7  data: {}
8})

发送 GET 请求

1// 查询数据
2const getApi = () => {
3  axios({
4    // 请求类型
5    method: "GET",
6    // URL
7    url: "http://127.0.0.1:3000/posts",
8  }).then((response) => {
9    console.log(response);
10  });
11};
12
13// GET请求简写方式
14const getApi = () => {
15  axios("http://127.0.0.1:3000/posts").then((response) => {
16    console.log(response);
17  });
18};

发送 POST 请求

1// 添加数据
2const postApi = () => {
3  const params = {
4    author: "dancy",
5    title: "学习axios",
6  };
7  axios({
8    // 请求类型
9    method: "POST",
10    // URL
11    url: "http://127.0.0.1:3000/posts",
12    // 设置请求体
13    data: params,
14  }).then((response) => {
15    console.log(response);
16  });
17};

发送 PUT 请求

1// 更新第二条数据
2const putApi = () => {
3  axios({
4    // 请求类型
5    method: "PUT",
6    // URL
7    url: "http://127.0.0.1:3000/posts/2",
8    // 设置请求体
9    data: {
10      author: "dancy",
11      title: "学习前端",
12    },
13  }).then((response) => {
14    console.log(response);
15  });
16};

发送 DELETE 请求

1// 删除第二条数据
2const deleteApi = () => {
3  axios({
4    // 请求类型
5    method: "DELETE",
6    // URL
7    url: "http://127.0.0.1:3000/posts/2",
8  }).then((response) => {
9    console.log(response);
10  });
11};