温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

axios中如何使用GET与POST

发布时间:2021-07-20 10:30:04 来源:亿速云 阅读:143 作者:小新 栏目:web开发

这篇文章主要介绍axios中如何使用GET与POST,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

axios

axios 是一个基于 Promise 的 HTTP 客户端,专门为浏览器和 node.js 服务

Vue 2.0 官方推荐使用 axios 来代替原来的 Vue request,所以这里介绍一下 axios 的功能和基本的使用方法,希望能够对各位所有帮助。^_^

功能

  • 在浏览器中发送 XMLHttpRequests 请求

  • 在 node.js 中发送 http 请求

  • 支持 Promise API

  • 拦截请求和响应

  • 转换请求和响应数据

  • 取消请求

  • 自动转换 JSON 数据格式

  • 客户端支持防范 XSRF 攻击

浏览器支持

axios 能够支持 IE7 以上的 IE 版本,同时能够支持大部分主流的浏览器,需要注意的是,你的浏览器需要支持 Promise,才能够使用 axios。所以比较好的做法是先安装 polyfill,然后再使用 axios。

安装

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用

这里以 Vue 为例:在 NPM 中安装 axios 之后,需要在 main.js 文件中引用 package

import axios from 'axios'

然后全局绑定

Vue.prototype.$http = axios

然后可以在 .vue 文件中使用 $http 来代替 axios

GET

// Make a request for a user with a given ID 
axios.get('/user?ID=12345')
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });

// Optionally the request above could also be done as 
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) {
  // Both requests are now complete 
 }));

当然,axios 的功能还包括 axios API、interceptor 等等,这里想要详细了解的可以查看官方文档:axios,后面陆续会介绍下 interceptor 的使用和各类参数的配置。

以上是“axios中如何使用GET与POST”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI