一个前端,爱跑步、爱吉他、爱做饭、爱生活、爱编程、爱南芳姑娘,爱我所爱。世间最温暖又无价的是阳光、空气与爱,愿它们能带你去更远的地方。

  • 文章
  • 心情
  • 照片墙
  • 留言板
  • 工具
  • 友链
  • biaoblog

    专注web开发技术分享

    axios,ajax,fetch请求示范

    技术 167 2022-05-26 10:02

    fetch:

          fetch("xxx", {
                    method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              name: "Hubot",
              login: "hubot",
            }),
          });
    

    上传文件:

     var formData = new FormData();
          formData.append("file", file);
          console.log(formData.get("file"));
          fetch("http://localhost:3000/blogData/upload", {
            method: "POST",
            body: formData,
          // headers: {
            // //不需要写'Content-Type': 'multipart/form-data',自动是form -data 写了报错!离谱!
            // 'Content-Type': 'multipart/form-data',
            // },
          })
            .then((res) => {
              return res.json();
            })
            .then((res) => {
              console.log(res);
            });
    

    axios:

    执行 GET 请求

    // 为给定 ID 的 user 创建请求
    axios.get('/user?ID=12345')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    // 上面的请求也可以这样做
    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    执行 POST 请求

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    执行多个并发请求

    function getUserAccount() {
      return axios.get('/user/12345');
    }
    
    function getUserPermissions() {
      return axios.get('/user/12345/permissions');
    }
    
    axios.all([getUserAccount(), getUserPermissions()])
      .then(axios.spread(function (acct, perms) {
        // 两个请求现在都执行完成
      }));
    

    添加heads:

            axios
              .post(`${baseUrl}/addData`, addData, {
                headers: {
                  "Content-Type": "application/json",
                },
              })
              .then(function (response) {
                console.log(response);
              })
              .catch(function (error) {
                console.log(error);
              });
    

    Content-Type为 application/x-www-form-urlencoded 时参数需要拼接

        .post(
          "xxxxx",
          // application/x-www-form-urlencoded 的data 需要字符串拼接
          // 如果是"application/json" 可以用对象
          `js_code=${js_code}&appid=x&secret=x&grant_type=x`,
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          }
        )
        .then((res) => {
          return res.data;
        })
        .catch((err) => {
          return err;
        });
    

    上传文件:Content-Type为 multipart/form-data

          let file = e.target.files[0];
          let formData = new FormData();
    
          formData.append("file", file);
          axios
            .post(`${baseUrl}/upload`, formData, {
              headers: {
                "Content-type": "multipart/form-data",
              },
            })
            .then(function (res) {
              console.log(res);
              // innerHTML(response);
            })
            .catch(function (error) {
              console.log(error);
            });
    

    ajax:

    $("#ajaxBtn").click(function(){
     $.ajax({
        url:"http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
          headers:{"appId":appId,"appKey":appKey,"Content-Type":"text/plain;charset=UTF,
        data:{action:"jQueryAjax"},
        type:"GET",
        success:function (data) {
        // alert("服务器返回的数据是:" + data);
        // var jsonObj = JSON.parse(data);
         $("#msg").html("编号:" + data.id + " , 姓名:" + data.name);
        },
        dataType : "json"
       });
      });
    

    文章评论

    评论列表(0