当前位置:   article > 正文

【axios】axios的基本使用_axios的使用

axios的使用

一、 Axios简介

1、 Axios是什么?

Axios是一个基于promise的HTTP库,类似于jQuery的ajax,用于http请求。可以应用于浏览器端和node.js,既可以用于客户端,也可以用于node.js编写的服务端。

2.、Axios特性

支持PromiseAPI
拦截请求与响应,比如:在请求前添加授权和响应前做一些事情。
转换请求数据和响应数据,比如:进行请求加密或者响应数据加密。
取消请求
自动转换JSON数据
客户端支持防御XSRF

二、安装使用

1、axios组件下载

npm install axios

2、引入axios

import axios from 'axios';

3、Axios常用得请求方法

get:一般用户获取数据
post:一般用于表单提交与文件上传
patch:更新数据(只将修改得数据推送到后端)
put:更新数据(所有数据推送到服务器)
delete:删除数据
备注:post一般用于新建数据,put一般用于更新数据,patch一般用于数据量较大的时候的数据更新。

4、Axios使用

4.1. GET传递参数 (get : 查询数据)

  1. //第一种方式
  2. axios.get('/query?name=tom')
  3. .then(function (response) {
  4. console.log(response);
  5. })
  6. //第二种方式
  7. axios.get('/query', {
  8. params: {
  9. name: 'tom'
  10. }
  11. }).then(function (response) {
  12. console.log(response);
  13. })
  14. //第三种方式
  15. axios({
  16. method: 'get',
  17. url: '/query',
  18. data: {
  19. name: 'tom',
  20. }
  21. }).then(function (response) {
  22. console.log(response);
  23. })
  24. //第四种方式
  25. axios.get('/adata/123')
  26. .then (ret => {
  27. console. log(ret. data)
  28. })

4.2.POST传递参数 (post : 添加数据)

通过选项传递参数(默认传递的是json格式的数据)

  1. axios.post('/query', {
  2. name: 'tom',
  3. icon: 'img_path'
  4. }).then(function (response) {
  5. console.log(response);
  6. })

4.3. DELETE传递参数 (delete :删除数据)

● 参数传递方式与GET类似

  1. //第一种方式
  2. axios.delete ( "/adata?id=123')
  3. .then (ret=> {
  4. console. log (ret. data )
  5. })
  6. //第二种方式
  7. axios. delete ('/adata/123 '
  8. .then (ret= => {
  9. console. log(ret. data)
  10. })
  11. //第三种方式
  12. axios. delete ('/adata ', {
  13. params :{
  14. id: 123
  15. }
  16. })
  17. .then (ret= => {
  18. console. log(ret. data)
  19. })
  20. //第四种方式
  21. axios({
  22. method: 'delete',
  23. url: '/query',
  24. data: {
  25. name: 'tom',
  26. }
  27. }).then(function (response) {
  28. console.log(response);
  29. })

4. 4PUT传递参数 (put : 修改数据)

● 参数传递方式与POST类似

  1. axios.put('/adata/123' , {
  2. uname:'tom',
  3. pwd: 123
  4. }) .then (ret= => {
  5. console. log(ret. data )
  6. })

5.axios的响应结果

响应结果的主要属性

● data :实际响应回来的数据
● headers :响应头信息
● status :响应状态码
● statusText :响应状态信息

响应结果

  1. axios.post ('/add').then (ret=> {
  2. console.log (ret)
  3. })

6.axios的全局配置

● axios.defaults.timeout = 3000; // 超时时间
● axios.defaults.baseURL = 'http://localhost:3000/app'; // 默认地址
● axios.defaults.headers[ ' mytoken' ]='aqwerwqwerqwer2ewrwe23eresdf23' // 设置请求头

代码分析

  1. //配置请求的基准URL地址
  2. axios.defaults.baseURL = 'http://127.0.0.1:3000/'
  3. //配置请求头信息
  4. axios.defaults.headers['mytoken'] = 'hello';
  5. axios.get('http://localhost:3000/axios-json').then(function(ret) {
  6. console.log(ret.data.uname)
  7. })

7.axios拦截器

1.请求拦截器

在请求发出之前设置一些信息

  1. / /添加一一个请求拦截器
  2. axios.interceptors.request.use (funct ion (config) {
  3. / /在请求发出之前进行些信息设置
  4. return config;
  5. }, function (err) {
  6. //处理响应的错误信息
  7. }) ;

请求拦截器 代码分析

  1. //axios请求拦截器
  2. axios.interceptors.request.use(function(config){
  3. console.log(config.url)
  4. config.headers.mytoken = 'nihao'
  5. return config
  6. },function(err){
  7. console.log(err)
  8. })
  9. //.then 返回服务器响应的数据
  10. axios.get('http://127.0.0.1:3000/adata').then(function(data){
  11. console.log(data)
  12. })

2.响应拦截器

在获取数据之前对数据做一些加工处理

响应拦截器 代码分析

  1. //axios响应式拦截器
  2. axios.interceptors.response.use(function(res) {
  3. // console.log(res)
  4. var data = res.data;
  5. return data;
  6. }, function(err) {
  7. console.log(err) //hello axios
  8. })
  9. axios.get('http://127.0.0.1:3000/adata').then(function(data) {
  10. console.log(data)
  11. })

8.一般开发会对axios二次封装进行使用(开发常用重点)

1,先创建一个文件夹

2.完整封装的request.js

  1. import axios from 'axios'
  2. import router from '@/router'
  3. //创建一个新的axios对象
  4. const request = axios.create({
  5. baseURL: process.env.VUE_APP_BASEURL, //后端接口地址统一前缀
  6. timeout: 30000
  7. })
  8. //request 拦截器
  9. //在请求发送前对请求做一些处理,比如统一加token,对请求参数统一加密
  10. request.interceptors.request.use(config => {
  11. console.log('process::',process)
  12. console.log('process.env::',process.env)
  13. console.log('baseURL::',process.env.VUE_APP_BASEURL)
  14. config.headers['Content-Type'] = 'application/json;charset=utf-8'; //设置参数请求类型
  15. let user = JSON.parse(localStorage.getItem("honey-user") || '{}')
  16. config.headers['token'] = user.token //设置请求头
  17. return config
  18. }, error => {
  19. console.error('request error: ' + error) // for debug
  20. return Promise.reject(error)
  21. });
  22. //response 拦截器
  23. //可以在接口响应后统一处理结果
  24. request.interceptors.response.use(response => {
  25. let res = response.data;
  26. // 兼容服务端返回的字符串数据
  27. if (typeof res === 'string') {
  28. res = res ? JSON.parse(res) : res
  29. }
  30. //后端code返回401的时候去登录页面
  31. if (res.code === '401') {
  32. router.push('/login');
  33. }
  34. return res;
  35. },
  36. error => {
  37. console.error('response error: ' + error) // for debug
  38. return Promise.reject(error)
  39. }
  40. )
  41. export default request

 3.分别创建两个文件,分别作为开发和生产的接口前缀路径

.env.development  开发地址

VUE_APP_BASEURL='http://localhost:9090'

.env.production  生产地址

VUE_APP_BASEURL='http://121.4.123.248/:9090'

4.main.js($request和$baseUrl全局使用)

将封装的$request和$baseUrl对象挂载到vue的实例对象上面

Vue.prototype.$request=request

Vue.prototype.$baseUrl=process.env.VUE_APP_BASEURL

这样在全局都可以使用这两个对象了$request和$baseUrl

5.直接使用

首先介绍一下localStroage()的使用方法。

存值:localStroage.setItem(“key”,“value”)
取值:localStroage.getItem(“key”)

 本地登录就是:

http://localhost:9090/login

服务器登录

http://121.4.123.248:9090/login

6.补充说明关于vue .env文件配置使用

https://blog.csdn.net/qq_41538097/article/details/117355115

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/829646
推荐阅读
相关标签
  

闽ICP备14008679号