请求封装(axios、fetch)

在前端发送请求到后台不同的框架与原生js发送请求的方式都不相同,比如我们在使用jquery时发送请求可以用jq中封装好的$.ajax,利用原生js向node发送请求时可以使用原生的ajax(我们也可以手动进行封装),在vue框架或react中可以使用axios或feach向后台发送请求,下面将对axios、feach进行简单封装。

一、axios

1、axios安装命令

npm install axios

2、封装好的axios

import axios from "axios";//下载并引入axios

const myAxios=axios.create({
    baseURL:'您的请求路径',
    timeout: 5000,//响应超时时间设置
    headers:{//设置请求头并携带token
        'Content-Type':'application/json',
        'token':sessionStorage.getItem('token')
    }
})
//请求拦截器
axios.interceptors.request.use(function (config){
    console.log(config)
    return config;
},function (error){
    return Promise.reject(error)
})

//响应拦截
axios.interceptors.response.use((response)=>{
    console.log(response)
    return response;//响应成功
},function (error){//响应失败
    switch (error.response.status){
        case 401://token有问题
            sessionStorage.clear()
            alert("重新登录");
            window.location.href="/"
            window.location.href="/login"
            break;
        case 400:
            break;
    }
})

export default myAxios //导出封装好的axios

3、其他页面应用

//post请求方式
axios.post('请求路径',{
          //您要发送给后台的数据
        username:'admin',
        pwd:'admin'
      }).then(rep=>{//请求成功返回的数据
        console.log(rep)
      })

二、fetch

1、安装命令

npm install whatwg-fetch -save

2、对fetch进行封装

import 'whatwg-fetch'//引入

//设置代理后的请求路径
const BASE_URL="/api";//基础请求路径,

//如果是get请求,需要将get请求的参数拼接成字符串 

const json2url=(json)=>{
    let arr=[];
    for(let name in json){
        arr.push(name+"="+json[name])
    }
    return arr.join("&")
}

const http=({url,method="get",params={},data={}})=>{

    if(!url)return;

    const token=sessionStorage.getItem("token") || "";//获取token(一般登录后存进去)

    let options={
        method,
        headers:{
            token
        },

    }

    //判断请求方式,默认使用get方式
    if(method=="post"){
        options.body=JSON.stringify(data)
    }

    //返回拼接好的路径
    return fetch(BASE_URL+url+"?"+json2url(params),options).then(response=>response.json())

}
export default http;//导出

3、其他页面使用

import http from '../../utils/http'//引入封装好的fetch
//登录请求
        http({
            url:"请求路径",
            params:values//请求参数
        }).then(res=>{//请求成功返回
            console.log(res);
        })
相关推荐
Vicky&James8 分钟前
WPF到Web的无缝过渡:英雄联盟客户端项目OpenSilver迁移实战
前端·wpf
m0_7482336412 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟20 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386321 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596022 分钟前
前端代理,解决跨域问题讲解
前端
quitv27 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238135 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星37 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端