Axios,是一个基于promise 的网络请求库,作用于node.js和浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。
1 安装axios
npm install axios
2 在项目的更目录创建一个 util文件,然后新建一个名为service.js 的文件
(注意点baseURL 是接口路径,请求根据请求不同进行设置,这里使用到了element-plus框架)
安装 element-plus框架
npm install element-plus --save
service.js文件代码如下
- import axios from "axios"
- import { ElLoading } from 'element-plus'
- import { ElMessage } from 'element-plus'
- // 使用create创建axios实例
- let loadingObj = null
- const Service = axios.create({
- timeout:8000,
- baseURL:"http:XXX",
- headers:{
- "Content-type":"application/json;charset=utf-8",
- }
- })
- // 请求拦截-增加loading,对请求做统一处理
- Service.interceptors.request.use(config=>{
- loadingObj=ElLoading.service({
- lock: true,
- text: 'Loading',
- background: 'rgba(0, 0, 0, 0.7)',
- })
- return config
- })
- // 响应拦截-对返回值做统一处理
- Service.interceptors.response.use(response=>{
- loadingObj.close()
- const data = response.data
- if(data.meta.status!=200 && data.meta.status!=201){
- ElMessage.error(data.meta.msg||"服务器出错")
- // 请求出错
- return data
- }
- return data
-
- },error=>{
- loadingObj.close()
- ElMessage({
- message:"服务器错误",
- type:"error",
- duration:2000
- })
- })
-
- // post请求
- export const post=config=>{
- return Service({
- ...config,
- method:"post",
- data:config.data
- })
- }
- // get请求
- export const get=config=>{
- return Service({
- ...config,
- method:"get",
- params:config.data
- })
- }
- // put请求
- export const put=config=>{
- return Service({
- ...config,
- method:"put",
- data:config.data
- })
- }// delete请求
- export const del=config=>{
- return Service({
- ...config,
- method:"delete"
- })
- }
3 接口文件 新建一个request.js 文件放入util文件夹中
- import {post,get,put,del} from "./service"
-
- export const loginApi = function(data) {
- return post({
- url:"/login",
- data
- })
- }
4 在具体页面使用中
- import {loginApi} from "@/util/request"
- export default {
- name:"login",
- setup(){
- const data=reactive({
- loginData:{
- username:"test",
- password:"1234"
- },
-
- })
- const handleLogin=()=>{
- // 请求后台接口
- loginApi(data.loginData).then(res=>{
- // todo
- })
-
- }
-
- return{
- ...toRefs(data),
- handleLogin
- }
- }
- }