Axios网络请求库学习笔记

Axios是一个基于promise的http网络请求库,可以用于浏览器和nodejs,在nodejs中使用http模块,而在浏览器使用XMLHttpRequests 支持promise api,支持拦截请求和响应,转换请求数据和响应数据,取消请求,自动转换json数据,支持防御XSRF攻击 安装 yarn add axios 实例demo import axios from "axios"; axios.get("https://httpbin.org/get", { params: { name: "root" } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); axios.post("https://httpbin.org/post", { name: "root", pass: "root" }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); 可以看到页面已经发送了get和post请求,.then和.catch分别表示请求成功和请求失败时调用的函数,也可以用箭头函数,其中response参数为请求的数据,error为错误信息 还可以写成这样 axios({ method: 'post', url: 'https://httpbin.org/post', data: { name: "root", pass: "root" } }); FormData方式 let data = { home: "hallo", main: "abc" } let formData = new FormData() for(let key in data){ formData....

2021-08-11 · 2 min · Me