当前位置: 首页 > Web前端 > vue.js

如何向axios添加自定义令牌字段?

时间:2023-03-31 21:42:03 vue.js

一般向后台发送请求获取数据时,需要带上token。有时您可能需要添加其他自定义字段。如何添加它其实很简单。下面以axios为例,为所有请求添加token字段。1、代码怎么写?letloading=null;//请求拦截axios.interceptors.request.use(config=>{loading=Loading.service({text:"Loading...",fullscreen:true});//这个token是随机编辑的lettoken="sdsklssdfkdlsfkkskjfskfj";//添加自定义令牌字段,mytokenconfig.headers.myToken=token;//添加其他自定义字段,otherParamsletotherParams="sdfsf44545456456";config.headers.otherParams=otherParams;returnconfig;},error=>{returnPromise.error(error);});添加后可以看到请求头有自定义字段myToken和otherParams:2.示例代码可以下载复制上面的代码运行看看效果。您也可以从GitHub下载它:https://github.com/Jackyyans/code123。更多示例将持续更新。欢迎关注。