当前位置:首页 » 数据仓库 » 前端如何配置全局axios
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

前端如何配置全局axios

发布时间: 2022-12-23 15:00:27

A. vue的http请求主要是用什么插件

axios

基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

功能特性

在浏览器中发送XMLHttpRequests请求

在 node.js 中发送http请求

支持PromiseAPI

拦截请求和响应

转换请求和响应数据

自动转换 JSON 数据

客户端支持保护安全免受XSRF攻击


安装

使用 bower:

$ bower install axios

使用 npm:

$ npm install axios

例子

发送一个GET请求

//
axios.get('/user?ID=12345')
.then(function(response){
console.log(response);
})
.catch(function(response){
console.log(response);
});
//
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(response){
console.log(response);
});

发送一个POST请求

axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(response){
console.log(response);
})
.catch(function(response){
console.log(response);
});

发送多个并发请求

functiongetUserAccount(){
returnaxios.get('/user/12345');
}
functiongetUserPermissions(){
returnaxios.get('/user/12345/permissions');
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread(function(acct,perms){
//Bothrequestsarenowcomplete
}));

axios API

可以通过给axios传递对应的参数来定制请求:

axios(config)
//SendaPOSTrequestaxios({method:'post',url:'/user/12345',
data:{firstName:'Fred',lastName:'Flintstone'}});
axios(url[,config])
//SnedaGETrequest(defaultmethod)
axios('/user/12345');


请求方法别名

为方便起见,我们为所有支持的请求方法都提供了别名

axios.get(url[,config])
axios.delete(url[,config])
axios.head(url[,config])
axios.post(url[,data[,config]])
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])

注意

当使用别名方法时,url、method和data属性不需要在 config 参数里面指定。

并发

处理并发请求的帮助方法

axios.all(iterable)

axios.spread(callback)

创建一个实例

你可以用自定义配置创建一个新的 axios 实例。

axios.create([config])
varinstance=axios.create({
baseURL:'https://some-domain.com/api/',
timeout:1000,
headers:{'X-Custom-Header':'foobar'
}});

实例方法

所有可用的实例方法都列在下面了,指定的配置将会和该实例的配置合并。

axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch(url[,data[,config]])

请求配置

下面是可用的请求配置项,只有url是必需的。如果没有指定method,默认的请求方法是GET。

{
//`url`
url:'/user',
//`method`
method:'get',//default
//`baseURL`willbeprependedto`url`unless`url`isabsolute.
//Itcanbeconvenienttoset`baseURL`
//tomethodsofthatinstance.
baseURL:'https://some-domain.com/api/',
//`transformRequest`
//'PUT','POST',and'PATCH'
//
transformRequest:[function(data){
//
returndata;
}],
//`transformResponse`
//itispassedtothen/catch
transformResponse:[function(data){
//
returndata;
}],
//`headers`arecustomheaderstobesent
headers:{'X-Requested-With':'XMLHttpRequest'},
//`params`
params:{
ID:12345
},
//`paramsSerializer``params`
//(e.g.https://www.npmjs.com/package/qs,http://api.jquery.com/jquery.param/)
paramsSerializer:function(params){
returnQs.stringify(params,{arrayFormat:'brackets'})
},
//`data`
//'PUT','POST',and'PATCH'
//Whenno`transformRequest`isset,mustbeastring,anArrayBufferorahash
data:{
firstName:'Fred'
},
//`timeout`.
//Iftherequesttakeslongerthan`timeout`,therequestwillbeaborted.
timeout:1000,
//`withCredentials`indicateswhetherornotcross-siteAccess-Controlrequests
//shouldbemadeusingcredentials
withCredentials:false,//default
//`adapter`.
//Call`resolve`or`reject`andsupplyavalidresponse(see[responsedocs](#response-api)).
adapter:function(resolve,reject,config){
/*...*/
},
//`auth`,andsuppliescredentials.
//Thiswillsetan`Authorization`header,overwritinganyexisting
//`Authorization`customheadersyouhavesetusing`headers`.
auth:{
username:'janedoe',
password:'s00pers3cret'
}
//`responseType`
//optionsare'arraybuffer','blob','document','json','text'
responseType:'json',//default
//`xsrfCookieName`
xsrfCookieName:'XSRF-TOKEN',//default
//`xsrfHeaderName`
xsrfHeaderName:'X-XSRF-TOKEN',//default
//`progress`'POST'and'PUTuploads'
//aswellas'GET'downloads
progress:function(progressEvent){
//
}
}

响应的数据结构

响应的数据包括下面的信息:

{
//`data`
data:{},
//`status`
status:200,
//`statusText`
statusText:'OK',
//`headers`
headers:{},
//`config`istheconfigthatwasprovidedto`axios`fortherequest
config:{}
}

当使用then或者catch时, 你会收到下面的响应:

axios.get('/user/12345')
.then(function(response){
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});

默认配置

你可以为每一个请求指定默认配置。

全局 axios 默认配置

axios.defaults.baseURL='https://api.example.com';
axios.defaults.headers.common['Authorization']=AUTH_TOKEN;
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';

自定义实例默认配置

//
varinstance=axios.create({
baseURL:'https://api.example.com'
});
//
instance.defaults.headers.common['Authorization']=AUTH_TOKEN;

配置的优先顺序

./defaults.js,,..Here'sanexample.
//
//`0`=axios.create();
//
//Nowallrequestswillwait2..defaults.timeout=2500;
//'sknowntotakealongtimeinstance.get('
/longRequest',{timeout:5000});

拦截器

你可以在处理then或catch之前拦截请求和响应

// 添加一个请求拦截器

axios.interceptors.request.use(function(config){
//
returnconfig;
},function(error){
//Dosomethingwithrequesterror
returnPromise.reject(error);
});



// 添加一个响应拦截器

axios.interceptors.response.use(function(response){
//Dosomethingwithresponsedata
returnresponse;
},function(error){
//Dosomethingwithresponseerror
returnPromise.reject(error);
});

移除一个拦截器:

varmyInterceptor=axios.interceptors.request.use(function(){/*...*/});
axios.interceptors.request.eject(myInterceptor);

你可以给一个自定义的 axios 实例添加拦截器:

varinstance=axios.create();
instance.interceptors.request.use(function(){/*...*/});

错误处理

axios.get('/user/12345')
.catch(function(response){
if(responseinstanceofError){
//
console.log('Error',response.message);
}else{
//Therequestwasmade,
//thatfallsoutoftherangeof2xx
console.log(response.data);
console.log(response.status);
console.log(response.headers);
console.log(response.config);
}
});

Promises

axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入polyfill

B. axios中的请求拦截器怎么用

vue-resource不再维护之后,我也用起了axios,但是死活无法设置服务器发送过来的cookie

后来查询文档发现,这个是要单独配置的。
// `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default
当我们把此配置项设置成默认配置项并且设置成true的时候,axios就可以设置cookies了。
全局默认配置设置方法:
axios.defaults.withCredentials=true
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

C. 前端环境的安装与配置

前端环境的安装与配置?一、工具安装
1.编辑器
2.Git(分布式的代码管理工具)
3.Photoshop
4.Nodejs链接
二、 环境配置
1.配置git:

1.1 设置Git的user name和email:
$ git config --global user.name "name"
$ git config --global user.email "[email protected]"
1.2 生成SSH密钥过程:(看需求配置)
$ ssh-keygen -t rsa -C "[email protected]"

3个回车,密码为空。
Your identification has been saved in /home/tekkub/.ssh/id_rsa.
Your public key has been saved in /home/tekkub/.ssh/id_rsa.pub.
The key fingerprint is:

………………

最后得到了两个文件:id_rsa和id_rsa.pub

添加密钥到ssh:

登陆gitlab, Profile Settings -> SSH Keys -> ADD SSH KEYS ,找到本地的id_rsa.pub文件,复制出里面的内容,添加到 key 内,此时 Title 会自动填上你的邮箱,没有的话手动填写, ADD KEY
1.3 拉取代码到本地(权限)

创建一个存放项目的文件夹,在该文件夹下,单击右键,选择git bash,打开git命令框,编写命令:git clone [email protected]:xx/xx.git(可以在gitlab项目中找到存放地址,gitlab地址:http://gitlab.vchangyi.com ),按回车,就可以从gitlab上clone代码到本地文件夹
1.4 手动安装nodejs,如果是pc端安装的话,nodejs版本不能过低。

安装最新版的话npm安装项目依赖会有问题,手机端gulp无法启动,所以建议安装nodejs V6。
1.5 测试node是否安装成功

在git 命令窗或者node 命令窗中输入命令 :node -v
1.6 同理,测试npm是否安装成功npm -v
1.7安装gulp

在项目下打开git 命令窗,从淘宝源上自行安装,这个时间需要等待和耐心,也会有网络原因导致安装失败,如果安装失败可以多来几次,直到成功为止。
如果是pc端:npm install --registry=http://registry.npm.taobao.org --phantomjs_cdnurl=http://cnpmjs.org/downloads

npm 安装时候 持久使用淘宝源 设置:
npm config set registry https://registry.npm.taobao.org
配置后可通过下面方式来验证是否成功
npm config get registry


npm info express