本文主要讲解axios的概念和基本使用。
axios时目前最流行的ajax封装库之一,用于很方便地实现ajax请求的发送。
支持的功能:
先借助json-server创建一个简单的服务,供ajax发送请求,json-server是一个简单的可以接收restful的服务。
github地址:https://github.com/typicode/json-server
第一步:安装:npm install -g json-server

第二步:创建一个名为db.json的文件,把网站的数据复制进去。
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
第三步:启动命令:json-server --watch db.json

访问http://localhost:3000/posts 下面页面为成功

GitHub地址:https://github.com/axios/axios

为了方便,我们直接使用第四种。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios基本使用</title>
</head>
<body>
<button id="btn1">发送get请求</button> <br><br>
<button id="btn2">发送post请求</button><br><br>
<button id="btn3">发送put请求</button><br><br>
<button id="btn4">发送delete请求</button>
<hr>
<div>其他发送请求的api:</div><br><br>
<button id="btn5">发送get请求1</button> <br><br>
<button id="btn6">发送post请求1</button><br><br>
<button id="btn7">发送put请求1</button><br><br>
<button id="btn8">发送delete请求1</button>
</body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
//发送get
document.getElementById("btn1").onclick = function(){
axios({
method:"GET",
url:"http://localhost:3000/posts/1"
}).then(response=>{
console.log(response);
})
};
//发送post
document.getElementById("btn2").onclick = function(){
axios({
method:"POST",
url:"http://localhost:3000/posts",
data:{
title:"axios学习",
author:"Yehaocong"
}
}).then(response=>{
console.log(response);
})
};
//发送put
document.getElementById("btn3").onclick = function(){
axios({
method:"PUT",
url:"http://localhost:3000/posts/2",
data:{
title:"axios学习",
author:"Liaoxiaoyan"
}
}).then(response=>{
console.log(response);
})
};
document.getElementById("btn4").onclick = function(){
axios({
method:"DELETE",
url:"http://localhost:3000/posts/2",
}).then(response=>{
console.log(response);
})
};
//其他发送请求的api
document.getElementById("btn5").onclick = function(){
//发送get,使用get,第一个参数时url,第二个参数时config配置对象
axios.get("http://localhost:3000/posts/1")
.then(response=>{
console.log(response);
})
};
//发送post
document.getElementById("btn6").onclick = function(){
//发送post请求,第一个参数时url,第二个参数时请求体,第三个参数时config配置对象
axios.post("http://localhost:3000/posts",
{title:"axios学习2",
author:"Yehaocong2"})
.then(response=>{
console.log(response);
})
};
//发送put,
document.getElementById("btn7").onclick = function(){
//发送put,接收三个参数,url 请求体 、 config配置对象
axios.put("http://localhost:3000/posts/2",{title:"axios学习",
author:"Liaoxiaoyan"})
.then(response=>{
console.log(response);
})
};
document.getElementById("btn8").onclick = function(){
//发送delete请求,接收2个参数, url config配置对象
axios.delete("http://localhost:3000/posts/3")
.then(response=>{
console.log(response);
})
};
//这个与axios({})基本相同
// axios.request({
// })
</script>
</html>
请求的响应结果结构分析:

{
// 路径url
url: '/user',
// 请求方法,默认get
method: 'get',
//基础url,最终请求的url是 baseURL+url拼接,所以再全局设置默认,可以使得发送请求时的url变得简洁
baseURL: 'https://some-domain.com/api/',
//设置请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
//设置请求url的query参数,可以使得url简洁。
//比如url是https://some-domain.com/api/user 然后params如下设置,那么最终的url是:
//https://some-domain.com/api/user?ID=12345&name=Jack
params: {
ID: 12345,
name:"Jack"
},
//设置请求体
data: {
firstName: 'Fred'
},
//设置请求的另外一种格式,不过这个是直接设置字符串的
data: 'Country=Brasil&City=Belo Horizonte',
//请求超时,单位毫秒,默认0,不超时。
timeout: 1000,
//响应数据类型,默认json
responseType: 'json',
//响应数据的编码规则,默认utf-8
responseEncoding: 'utf8',
//响应体的最大长度
maxContentLength: 2000,
// 请求体的最大长度
maxBodyLength: 2000,
//设置响应状态码为多少时是成功,调用resolve,否则调用reject失败
//默认是大于等于200,小于300
validateStatus: function (status) {
return status >= 200 && status < 300;
},
可以设置全局默认配置,是为了避免多种重复配置在不同请求中重复,比如baseURL、timeout等,这里设置baseURL。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>默认配置</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
axios.defaults.baseURL="http://localhost:3000";
//因为上面配置了baseURL,所以我们之后的请求只需要配置url不用像之前那样的全路径
axios.get("/posts/1")
.then(response=>{
console.log(response);
})
</script>
</body>
</html>

实质就是函数。
分为两种类型:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios拦截器</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
//这个是设置请求拦截器的api,传入两个回调,第一个成功回调,第二个失败回调。
axios.interceptors.request.use(
function(config){
console.log("请求拦截器1调用成功");
return config;
},
function(error){
console.log("请求拦截器1调用失败");
return Promise.reject(error)
}
)
//这个是设置响应拦截器的api,第一个成功回调,第二个失败回调
axios.interceptors.response.use(
function(response){
console.log("响应拦截器1调用成功");
return response;
},
function(error){
console.log("响应拦截器1调用失败");
return Promise.reject(error);
}
)
axios.get("http://localhost:3000/posts/1")
.then(function(response){
//
console.log("请求回调成功");
}).catch(function(error){
console.log("请求回调失败");
})
</script>
</body>
</html>
效果:

要理解这些个拦截器需要由一定的es6 Promise基础,出现上面效果的原因是,发送请求前,请求被请求拦截器拦截了,并且请求拦截器返回了一个非Promise实例的对象config,所以下一个拦截器是调用成功回调的,所以就打印响应拦截器成功,然后响应拦截器成功的回调返回的是非Promise实例的对象response,所以最终的请求回调是调用成功的回调,所以返回请求调用成功。
尝试以下再请求拦截器的成功回调中,返回reject状态的Promise。

效果:

出现上面效果的原因是,请求拦截器的成功回调中最后返回了reject状态的Promise实例对象,被判断为失败,到了回调链的下一回调,也就是响应拦截器的回调时,调用的时失败的回调,失败的回调中又返回了reject状态的Promise实例对象,所以到了真正请求的回调页调用了失败回调。
上面的效果与Promise如出一辙。
多个拦截器的效果:加了一个请求拦截器一个响应拦截器:


可以看到请求拦截器类似栈,后进先出,响应拦截器类似队列,先进先出。
可以在请求拦截器中对config进行调整,比如添加一个超时什么的,可以在响应拦截器中对response返回值进行调整,比如我返回到回调函数中只想要响应体部分。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios拦截器</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
//这个是设置请求拦截器的api,传入两个回调,第一个成功回调,第二个失败回调。
axios.interceptors.request.use(
function(config){
console.log("请求拦截器1调用成功");
return config;
},
function(error){
console.log("请求拦截器1调用失败");
return Promise.reject(error)
}
)
axios.interceptors.request.use(
function(config){
//设置请求超时时间
config.timeout = 5000;
console.log("请求拦截器2调用成功");
return config;
},
function(error){
console.log("请求拦截器2调用失败");
return Promise.reject(error)
}
)
//这个是设置响应拦截器的api,第一个成功回调,第二个失败回调
axios.interceptors.response.use(
function(response){
console.log("响应拦截器1调用成功");
console.log(response);
//返回到请求回调时,只要data数据
return response.data;
},
function(error){
console.log("响应拦截器1调用失败");
return Promise.reject(error);
}
)
axios.interceptors.response.use(
function(response){
console.log("响应拦截器2调用成功");
return response;
},
function(error){
console.log("响应拦截器2调用失败");
return Promise.reject(error);
}
)
axios.get("http://localhost:3000/posts/1")
.then(function(response){
//
console.log("请求回调成功");
console.log(response);
}).catch(function(error){
console.log("请求回调失败");
})
</script>
</body>
</html>
效果:

取消请求就是发送了请求后,等待一段时间得不到回应,可以取消他。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios取消请求</title>
</head>
<body>
<button id="btn1">发送请求</button>
<button id="btn2">取消请求</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
//第一步:定义一个全局的cancel变量,初始值是null
let cancel = null;
document.getElementById("btn1").onclick = function(){
axios.get("http://localhost:3000/posts/1",
{
//第二步:在请求的配置对象中,配置cancelToken属性值,并把函数的c参数赋值给全局变量cancel
cancelToken:new axios.CancelToken(function(c){
cancel = c;
})
})
.then(function(response){
//
console.log(response);
}).catch(function(error){
console.log("请求回调失败");
})
}
document.getElementById("btn2").onclick = function(){
//第三步:调用cancel函数就是取消请求接收
cancel();
}
</script>
</body>
</html>
需要把服务器的响应时间调到3秒,不然太快的话,演示不了取消请求。。
json-server --watch db.json -d 3000

我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po