请求封装(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);
        })
相关推荐
Fan_web11 分钟前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常13 分钟前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇1 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
Jiaberrr1 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho2 小时前
【TypeScript】知识点梳理(三)
前端·typescript
安冬的码畜日常3 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
太阳花ˉ3 小时前
html+css+js实现step进度条效果
javascript·css·html
小白学习日记4 小时前
【复习】HTML常用标签<table>
前端·html
john_hjy4 小时前
11. 异步编程
运维·服务器·javascript