安装axios
npm install axios
一、axios.get
对于请求参数携带有两种方式:
//方式一:直接写在第一个参数url的后面 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); //方式二:写在第二个参数中以对象的形式,属性为params axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
示例
<body> <script src="https://unpkg.com/axios@0.21.1/dist/axios.min.js"></script> <script> const url = "https://www.imooc.com/api/http/search/suggest?word=ajax"; axios.get(url, { params: { username: 'changlu' } }).then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); </script> </body>
二、POST请求
对于POST请求,axios会根据的data类型来为你自动设置Content-Type。当然你也可以自己来主动设置内容类型。
data为字符串如:"age=18&sex=男",Content-Type自动设置为application/x-www-form-urlencoded
data为对象如:{ sex: 'women', tel: '123'},就会自动设置为application/json。
注意:对于Content-Type: application/json这种类似请求,需要后端设置一个响应头如下,否则也会被浏览器拦截到。
方式一:采用axios构造器自动配置的形式发送ajax请求
<body> <script src="https://unpkg.com/axios@0.21.1/dist/axios.min.js"></script> <script> // const url = "https://www.imooc.com/api/http/json/search/suggest?word=ajax"; //后端对于application/json处理过的接口 const url = "https://www.imooc.com/api/http/json/search/suggest?word=ajax"; //后端对于application/json没有处理,只响应application/x-www-form-urlencoded的get请求 // 方式一:采用axios构造器自动配置的形式发送ajax请求 axios(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, // 请求参数 params: { username: 'changlu' }, // 请求体携带参数 data: "age=18&sex=男" }).then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); </script> </body>
方式二:采用axios.post(url,请求体)
参数二传入对象:
<script src="https://unpkg.com/axios@0.21.1/dist/axios.min.js"></script> <script> // const url = "https://www.imooc.com/api/http/json/search/suggest?word=ajax"; //后端对于application/json处理过的接口 const url = "https://www.imooc.com/api/http/search/suggest?word=ajax"; //后端对于application/json没有处理,只响应application/x-www-form-urlencoded的get请求 // 调用axios.post发出请求,在第二个参数中只能传入请求体内容,如对象或字符串形式,axios会根据类型来帮你自动设置content-type // 1、传入对象,默认帮你设置content-type为application/json;charset=utf-8 axios.post(url, { name: 'changlu', age: 18 }).then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); </script>
参数二传入字符串:
//对于传入字符串形式的,自动会给你设置content-type为application/x-www-form-urlencoded axios.post(url, "name=changlu&age=18") .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });
总结
对于axios这个第三方库帮我们封装的很好了,会自动帮你设置一些请求头等信息,并且你可以进行一系列的相关配置等等,都可以见官网即可!!!