草庐IT

网络请求库 – axios库

未路过 2023-03-28 原文

1.认识Axios库

Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中发送网络请求。

1.1 Axios的优点

XMLHttpRequest,fetch是高级一点的原生
原生的缺点:
1.需要自己来封装原生。
2.原生某些功能不具备,你需要自己来完成请求拦截,响应拦截等。
3.js可以跑在浏览器和node上面,但是原生的fetch是不能工作在node中,node需要使用别的api。比如http模块来发送请求。

使用axios的优点
1.已经帮我们把原生的底层逻辑都封装了。
2.还额外增加了拦截器等功能
3.适配浏览器和node。axios已经帮我们封装好了,在在浏览器中发送 XMLHttpRequests 请求,在 node.js 中发送 http请求。不用担心在不同的平台使用不同的api

1.2 功能特点

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 等等

1.3 安装axios

在项目中安装axios
npm install axios

2.发送常见的请求和配置

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])

在main.js中

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'

const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')

//1.发送request请求
axios
  .request({
    url: 'http://123.207.32.32:8000/home/multidata',
    method: 'get'
  })
  .then((res) => {
    console.log('res: ', res.data)
  })

//request里面的参数中的method里面写get的话,就和axios.get一样了,method不写的话,默认是get

//2.发送get请求(带参数有两种写法,第二种用的比较多)
axios.get('http://123.207.32.32:9001/lyric?id=500665346').then((res) => {
  console.log('res: ', res.data)
})

axios
  .get('http://123.207.32.32:9001/lyric', {
    params: {
      id: 500665346
    }
  })
  .then((res) => {
    console.log('res: ', res.data)
  })

//3.post 请求(2种方法)
axios
  .post('http://123.207.32.32:1888/02_param/postjson', {
    name: 'why',
    age: 18,
    height: 1.88
  })
  .then((res) => {
    console.log('res: ', res.data)
  })
//这种写法第二个 参数是data

//4.post请求方法二,直接把第二个参数当作config, 把data写道config里面
axios
  .post('http://123.207.32.32:1888/02_param/postjson', {
    data: {
      name: 'why',
      age: 18,
      height: 1.88
    }
  })
  .then((res) => {
    console.log('res: ', res.data)
  })

httpbin.org/get发送get 请求,httpbin.org/post发送post请求
用来做测试

3.常见的配置选项

image.png

3.1baseURL

import axios from 'axios'

const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')

//发送多个请求,后面的地址是不一样的,baseURL可以解决这个问题
// 给axios实例配置公共的基础配置
const baseURL = 'http://123.207.32.32:8000'
axios.defaults.baseURL = baseURL
//也可以配置timeout
axios.defaults.timeout = 10000
//axios.defaults.headers = {}

//1.1 get:/home/multidata
//自动拼接,实际上是http://123.207.32.32:8000/home/multidata
axios.get('/home/multidata').then((res) => {
  console.log('res: ', res.data)
})

3.2 axios.all

◼ 有时候, 我们可能需求同时发送两个请求

  • 使用axios.all, 可以放入多个请求的数组.
    希望数据都有请求之后再拿到数据
  • axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2
// 2.axios发送多个请求
//本质就是使用了 Promise.all
axios
  .all([
    axios.get('/home/multidata'),
    axios.get('http://123.207.32.32:9001/lyric?id=500665346')
  ])
  .then((res) => {
    console.log('res:', res)
  })

image.png

4.创建axios实例

◼ 为什么要创建axios的实例呢?

  • 当我们从axios模块中导入对象时, 使用的实例是默认的实例;
  • 当给该实例设置一些默认配置时, 这些配置就被固定下来了.
  • 但是后续开发中, 某些配置可能会不太一样;
  • 比如某些请求需要使用特定的baseURL或者timeout等.
  • 这个时候, 我们就可以创建新的实例, 并且传入属于该实例的配置信息.

直接这么使用,这里axios也是一个实例,是axios默认库提供给我们的实例,实际项目种不使用这个实例来发送请求,所有的请求都是一样的设置。

import axios from 'axios'
axios
  .request({
    url: 'http://123.207.32.32:8000/home/multidata',
    method: 'get'
  })
  .then((res) => {
    console.log('res: ', res.data)
  })
// axios默认库提供给我们的实例对象
axios.get("http://123.207.32.32:9001/lyric?id=500665346")

// 创建其他的实例发送网络请求
const instance1 = axios.create({
  baseURL: "http://123.207.32.32:9001",
  timeout: 6000,
  headers: {}
})

instance1.get("/lyric", {
  params: {
    id: 500665346
  }
}).then(res => {
  console.log("res:", res.data)
})

const instance2 = axios.create({
  baseURL: "http://123.207.32.32:8000",
  timeout: 10000,
  headers: {}
})

5.请求和响应拦截器

◼ axios的也可以设置拦截器:拦截每次请求和响应
axios.interceptors.request.use(请求成功拦截, 请求失败拦截)
// fn1: 请求发送成功会执行的函数
// fn2: 请求发送失败会执行的函数

◼ axios.interceptors.response.use(响应成功拦截, 响应失败拦截)
// fn1: 数据响应成功(服务器正常的返回了数据 200或者200多,都是成功的状态)
//fn2:服务器响应400+或者500+的时候调用这个函数

//对实例配置拦截器

//两个参数,一个请求成功的回调拦截,一个是请求失败的回调拦截
axios.interceptors.request.use(
  (config) => {
//config是发送请求时候的参数,并且用完之后要给人家返回出去
//用的时候可以做一些别的操作,比如改变config.url=XXX之类的,变换地址

    console.log('请求成功拦截')
    // 1.开始loading的动画

    // 2.对原来的配置进行一些修改
    // 2.1. header
    // 2.2. 认证登录: token/cookie
    // 2.3. 请求参数进行某些转化
    return config
  },
  (err) => {
    console.log('请求失败拦截')
    return err
  }
)
axios.interceptors.response.use(
  (res) => {
    console.log('响应成功的拦截')
    return res
  },
  (err) => {
    console.log('服务器响应失败')
    return err
  }
)

axios.interceptors.response.use(
  (res) => {////这个res是响应回来的数据
    console.log('响应成功拦截')
    // 1.结束loading的动画

    // 2.对数据进行转化, 再返回数据
    return res.data
  },
  (err) => {
    console.log('服务器响应失败')
    return err
  }
)

axios.get(`http://123.207.32.32:9001/lyric?id=500665346`).then((res) => {
  console.log('res:', res)
})

6.axios请求库封装(简洁版)

在src文件夹里面创建service文件夹
与服务器沟通有关的文件放里面
创建index.js

import axios from "axios";

class HYRequest {
  constructor(baseURL, timeout = 10000) {
    this.instance = axios.create({
      baseURL,
      timeout,
    });
  }
  request(config) {
    return this.instance.request(config).then((res) => {
      return res.data;
    });
  }
  get(config) {
    return this.request({ ...config, method: "get" });
  }
  post(config) {
    return this.request({ ...config, method: "post" });
  }
}

export default new HYRequest("http://123.207.32.32:9001");

main.js

import { createApp } from "vue";
import axios from "axios";
import App from "./App.vue";
import hyRequest from "./service";

createApp(App).mount("#app");

hyRequest
  .request({
    url: "/lyric?id=500665346",
  })
  .then((res) => {
    console.log("res:", res);
  });

hyRequest
  .get({
    url: "/lyric",
    params: {
      id: 500665346,
    },
  })
  .then((res) => {
    console.log("res:", res);
  });

有关网络请求库 – axios库的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  3. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  4. 网络编程套接字 - 2

    网络编程套接字网络编程基础知识理解源`IP`地址和目的`IP`地址理解源MAC地址和目的MAC地址认识端口号理解端口号和进程ID理解源端口号和目的端口号认识`TCP`协议认识`UDP`协议网络字节序socket编程接口`sockaddr``UDP`网络程序服务器端代码逻辑:需要用到的接口服务器端代码`udp`客户端代码逻辑`udp`客户端代码`TCP`网络程序服务器代码逻辑多个版本服务器单进程版本多进程版本多线程版本线程池版本服务器端代码客户端代码逻辑客户端代码TCP协议通讯流程TCP协议的客户端/服务器程序流程三次握手(建立连接)数据传输四次挥手(断开连接)TCP和UDP对比网络编程基础知识

  5. ruby - HTTP 请求中的用户代理,Ruby - 2

    我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)

  6. ruby-on-rails - 获取并发布相同匹配项的请求 - 2

    在我的路线文件中我有:match'graphs/(:id(/:action))'=>'graphs#(:action)'如果是GET请求(工作)或POST请求(不工作),我想匹配它我知道我可以使用以下方法在资源中声明POST请求:post'/'=>:show,:on=>:member但是我怎样才能为比赛做到这一点呢?谢谢。 最佳答案 如果你同时想要POST和GETmatch'graphs/(:id(/:action))'=>'graphs#(:action)',:via=>[:get,:post]编辑默认值可以设置如下match'g

  7. ruby - 检查网络文件是否存在,而不下载它? - 2

    是否可以在不实际下载文件的情况下检查文件是否存在?我有这么大的(~40mb)文件,例如:http://mirrors.sohu.com/mysql/MySQL-6.0/MySQL-6.0.11-0.glibc23.src.rpm这与ruby​​不严格相关,但如果发件人可以设置内容长度就好了。RestClient.get"http://mirrors.sohu.com/mysql/MySQL-6.0/MySQL-6.0.11-0.glibc23.src.rpm",headers:{"Content-Length"=>100} 最佳答案

  8. ruby - 404 未找到,但可以从网络浏览器正常访问 - 2

    我在这方面尝试了很多URL,在我遇到这个特定的之前,它们似乎都很好:require'rubygems'require'nokogiri'require'open-uri'doc=Nokogiri::HTML(open("http://www.moxyst.com/fashion/men-clothing/underwear.html"))putsdoc这是结果:/Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:353:in`open_http':404NotFound(OpenURI::HT

  9. ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型 - 2

    我试图像这样在我的测试用例中执行获取:request.env['CONTENT_TYPE']='application/json'get:index,:application_name=>"Heka"虽然,它失败了:ActionView::MissingTemplate:Missingtemplatealarm_events/indexwith{:handlers=>[:builder,:haml,:erb,:rjs,:rhtml,:rxml],:locale=>[:en,:en],:formats=>[:html]尽管在我的Controller中我有:respond_to:html,

  10. 深度学习12. CNN经典网络 VGG16 - 2

    深度学习12.CNN经典网络VGG16一、简介1.VGG来源2.VGG分类3.不同模型的参数数量4.3x3卷积核的好处5.关于学习率调度6.批归一化二、VGG16层分析1.层划分2.参数展开过程图解3.参数传递示例4.VGG16各层参数数量三、代码分析1.VGG16模型定义2.训练3.测试一、简介1.VGG来源VGG(VisualGeometryGroup)是一个视觉几何组在2014年提出的深度卷积神经网络架构。VGG在2014年ImageNet图像分类竞赛亚军,定位竞赛冠军;VGG网络采用连续的小卷积核(3x3)和池化层构建深度神经网络,网络深度可以达到16层或19层,其中VGG16和VGG

随机推荐