资讯专栏INFORMATION COLUMN

axios 封装和使用

Airmusic / 2976人阅读

摘要:当然不限于此种写法,还有其他的写法可网上搜索封装参考执行异步请求发请求配置对象指定请求参数发请求如果成功了调用如果失败了不调用而是提示异常信息请求出错了要求能根据接口文档定义接口请求包含应用中所有接口请求函数的模块每个函数的返回值都是基本要

当然不限于此种写法,还有其他的写法可网上搜索axios封装参考
//api/axios.js

import axios from "axios"
import {message} from "antd"

export default function ajax(url, data={}, type="GET") {

return new Promise((resolve, reject) => {

let promise
// 1. 执行异步ajax请求
if(type==="GET") { // 发GET请求
  promise = axios.get(url, { // 配置对象
    params: data // 指定请求参数
  })
} else { // 发POST请求
  promise = axios.post(url, data)
}
// 2. 如果成功了, 调用resolve(value)
promise.then(response => {
  resolve(response.data)
// 3. 如果失败了, 不调用reject(reason), 而是提示异常信息
}).catch(error => {
  // reject(error)
  message.error("请求出错了: " + error.message)
})

})

}

// api/index.js
/*
要求: 能根据接口文档定义接口请求
包含应用中所有接口请求函数的模块
每个函数的返回值都是promise

基本要求: 能根据接口文档定义接口请求函数
*/
import jsonp from "jsonp"
import {message} from "antd"
import ajax from "./ajax"

// const BASE = "http://localhost:5000"
const BASE = ""
// 登陆
/*
export function reqLogin(username, password) {
return ajax("/login", {username, password}, "POST")
}*/
export const reqLogin = (username, password) => ajax(BASE + "/login", {username, password}, "POST")

// 获取一级/二级分类的列表
export const reqCategorys = (parentId) => ajax(BASE + "/manage/category/list", {parentId})

// 添加分类
export const reqAddCategory = (categoryName, parentId) => ajax(BASE + "/manage/category/add", {categoryName, parentId}, "POST")

// 更新分类
export const reqUpdateCategory = ({categoryId, categoryName}) => ajax(BASE + "/manage/category/update", {categoryId, categoryName}, "POST")

// 获取一个分类
export const reqCategory = (categoryId) => ajax(BASE + "/manage/category/info", {categoryId})

// 获取商品分页列表
export const reqProducts = (pageNum, pageSize) => ajax(BASE + "/manage/product/list", {pageNum, pageSize})

// 更新商品的状态(上架/下架)
export const reqUpdateStatus = (productId, status) => ajax(BASE + "/manage/product/updateStatus", {productId, status}, "POST")

/*
搜索商品分页列表 (根据商品名称/商品描述)
searchType: 搜索的类型, productName/productDesc
*/
export const reqSearchProducts = ({pageNum, pageSize, searchName, searchType}) => ajax(BASE + "/manage/product/search", {
pageNum,
pageSize,

})

// 搜索商品分页列表 (根据商品描述)
/*export const reqSearchProducts2 = ({pageNum, pageSize, searchName}) => ajax(BASE + "/manage/product/search", {
pageNum,
pageSize,
productDesc: searchName,
})*/

// 删除指定名称的图片
export const reqDeleteImg = (name) => ajax(BASE + "/manage/img/delete", {name}, "POST")

// 添加/修改商品
export const reqAddOrUpdateProduct = (product) => ajax(BASE + "/manage/product/" + ( product._id?"update":"add"), product, "POST")
// 修改商品
// export const reqUpdateProduct = (product) => ajax(BASE + "/manage/product/update", product, "POST")

// 获取所有角色的列表
export const reqRoles = () => ajax(BASE + "/manage/role/list")
// 添加角色
export const reqAddRole = (roleName) => ajax(BASE + "/manage/role/add", {roleName}, "POST")
// 添加角色
export const reqUpdateRole = (role) => ajax(BASE + "/manage/role/update", role, "POST")

// 获取所有用户的列表
export const reqUsers = () => ajax(BASE + "/manage/user/list")
// 删除指定用户
export const reqDeleteUser = (userId) => ajax(BASE + "/manage/user/delete", {userId}, "POST")
// 添加/更新用户
export const reqAddOrUpdateUser = (user) => ajax(BASE + "/manage/user/"+(user._id ? "update" : "add"), user, "POST")

/*
json请求的接口请求函数
*/
export const reqWeather = (city) => {

return new Promise((resolve, reject) => {

const url = `http://api.map.baidu.com/telematics/v3/weather?location=${city}&output=json&ak=3p49MVra6urFRGOT9s8UBWr2`
// 发送jsonp请求
jsonp(url, {}, (err, data) => {
  console.log("jsonp()", err, data)
  // 如果成功了
  if (!err && data.status==="success") {
    // 取出需要的数据
    const {dayPictureUrl, weather} = data.results[0].weather_data[0]
    resolve({dayPictureUrl, weather})
  } else {
    // 如果失败了
    message.error("获取天气信息失败!")
  }

})

})
}
// reqWeather("北京")
/*
jsonp解决ajax跨域的原理
1). jsonp只能解决GET类型的ajax请求跨域问题
2). jsonp请求不是ajax请求, 而是一般的get请求
3). 基本原理
浏览器端:

  动态生成                
阅读需要支付1元查看
<