react+antd从头搭建管理台(三)请求后端接口封装

2 篇文章 0 订阅

1、安装请求插件

npm i axios

2、util文件夹下新建request.js,封装request请求行数

import axios from 'axios'
//创建一个axios
const instance = axios.create({
    baseURL:"http://localhost:8089",
    timeout:50000
})

//定义一些请求方法
export function get(url,params){
    return instance.get(url,{
        params
    })
}

export function post(url,data){
    return instance.post(url,data)
}

export function put(url,data){
    return instance.put(url, data)
}

export function del(url){
    return instance.delete(url)
}

由于每次都要传一个token值,所以对instance做一个全局拦截

访问axios官方网站

GitHub - axios/axios: Promise based HTTP client for the browser and node.js

把全局请求和全局响应的一个拦截复制粘贴下来

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

把axios改成instance,并在请求里面添加此配置config.headers['authorization']='Bearer '+getToken()

在文件头部引入import { getToken } from './auth'; 依赖

改写完request.js文件后内容如下

import axios from 'axios'
 
const instance = axios.create({
    baseURL:"http://localhost:8089",
    timeout:50000
})
// Add a request interceptor
// 全局请求拦截
instance.interceptors.request.use(function (config) {
    // Do something before request is sent
    config.headers['authorization']='Bearer '+getToken()
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
// 请求返回之后拦截
instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });
/**
 * get 请求
 * @param {*} url 
 * @param {*} params 
 * @returns 
 */
export function get(url,params){
    return instance.get(url,{
        params
    })
}

export function post(url,data){
    return instance.post(url,data)
}

export function put(url,data){
    return instance.put(url, data)
}

export function del(url){
    return instance.delete(url)
}

3、src文件下新建services文件夹,封装服务

services文件下新建auth.js做登录用

import {post} from '../utils/request'
/**
 * 用户登录
 * @param {*} user 
 * username
 * password
 * @returns 
 */
export function loginApi(user){
    return post('/api/v1/auth/manage_login',user)
}

再写一个products.js商品的

import { get,post,put } from "../utils/request"

export function listApi(pageNum,pageSize){
    return get("/api/v1/admin/products",{pageNum,pageSize})
}

// export function listApi(page = 1){
//     return get("/api/v1/admin/products",{page})
// }

export function createApi(data){
    return post('/api/v1/admin/createProducts',data)
}

export function modifyOne(id,data){
    return put('/api/v1/admin/products/'+id,data)
}

export function delOne(id){
    return put('/api/v1/admin/products/'+id)
}

export function getOneById(id){
    return get('/api/v1/admin/productInfo?productId='+id)
}

使用封装好的请求和服务

在Login.js中

引用login.js

import {loginApi} from '../services/auth'

const onFinish = (values: any) => {
        // setToken(values.username)
        // props.history.push("/admin")
        loginApi({
            userName: values.username,
            passWord: values.password
        }).then(
            res=>{
              if(res.data.code===200){
                message.success("登录成功! ")
                setToken(res.data.content)
props.history.push('/admin')
              }else{
                message.info('用户名或密码错误!')
              }
            }
        )
        .catch(
          err =>{
            message.error("用户不存在")
          }
        )


      };

登录成功,存储token并做路由跳转

源码地址 

https://github.com/gogocomeon/stu-shop-manager

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值