js 函数封装axios请求,get,post请求

什么是 axios?

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

  • axios.get(url[, config])
  • axios.post(url[, data[, config]])

怎么使用?

  • cdn引入
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
  • 安装包下载
npm install axios --save

函数封装

// ESlint检测语法
import axios from 'axios'
import { Toast } from 'vant'
import Vue from 'vue'
Vue.use(Toast)
const baseURL = 'http://XXXXX'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 默认表单提交
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 添加请求拦截器
// instance.interceptors.request.use(function (config) {
//   // 在发送请求之前做些什么
//   // 如果你没有登录,项目中任何页面你都进不去-后台管理系统

//       // 自定义加载图标
//     Toast.loading({
//       message: '加载中...',
//       forbidClick: true,
//       loadingType: 'spinner'
//     });

//   return config;
// }, function (error) {
//   // 对请求错误做些什么
//   return Promise.reject(error);
// });

//   // 添加响应拦截器
//   instance.interceptors.response.use(function (response) {
//     // 对响应数据做点什么

//     Toast.clear()

//     return response;
//   }, function (error) {
//     // 对响应错误做点什么
//     return Promise.reject(error);
//   });

const request = ({
  url,
  method = 'GET',
  params,
  data,
  withCredentials = false, // default
  headers
}) => {
  return new Promise((resolve, reject) => {
    // 区别两个不同的数据请求就行get,post
    switch (method.toUpperCase()) {
      case 'POST':
        var realData = {}
        if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {
          // 表单提交
          const p = new URLSearchParams()
          for (const key in data) {
            p.append(key, data[key])
          }
          realData = p
        } else {
          // json提交
          realData = data
        }
        instance.post(url, data = realData, {
          withCredentials, // default
          headers
        }).then(res => resolve(res))
          .catch(err => reject(err))
        break
      default:
        instance.get(url, {
          method,
          params,
          withCredentials, // default
          headers
        }).then(res => resolve(res))
          .catch(err => reject(err))
        break
    }
  })
}

export default request

// export default request   es6 模块导出
// module.exports = request   node.js 模块导出

可以测试一下的哦!

get请求

request({
        url: '/search',
        params: {
          a: 1,
          b: 2
       }
   }).then( res => console.log( res ))
        .catch( err => console.log( err ))

post请求

request({
       url: '/users',
       method: 'post',
       data: {
         a: 1,
         b: 2,
       },
       headers: {
         'Content-Type': 'application/json'
         // 'Content-Type': 'x-www-form-urlencoded' //表单
       }
    }).then( res => console.log( res ))
        .catch( err => console.log( err ))

顺便说一下fetchd的请求

  1. 原生js提供,可以说ajax封装版本,用起来简易
  2. 符合模块化思想
  3. 在浏览器中呈现的fetch字样
  4. fetch也是promise
  5. fetch返回值是没有经过封装的,安全度比axios要低
const baseURL = 'http://xxxx:3000' 


//get 请求
fetch(`${ baseURL }/search?name=aaa`,{
    method: 'GET'
   })
     .then( data => data.json() ) // 数据格式化    json()  text()   blob() 二进制格式化
     .then( res => console.log( res )) // res就是得到的真正的数据
     .catch( err => console.log( err ))


//post 表单请求

fetch(`${ baseURL }/users`,{
    method: 'POST',
     headers: new Headers({
       'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
     }),
     body: new URLSearchParams([["username", 'aaa'],["password", 123]]).toString() // 这里是请求对象
   })
     .then( data => data.json() ) 
     .then( res => console.log( res )) 
     .catch( err => console.log( err ))


//post json请求
fetch(`${ baseURL }/users`, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify({
      username: 'aaa',
      password: 123
    }), // data can be `string` or {object}!
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  }).then(res => res.json())
    .then( res => console.log( res )) 
    .catch( err => console.log( err ))


怎么解决跨域问题呢?(常见)

  • 后端代理-设置请求头
response.setHeader("Access-Control-Allow-Origin", "*");
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值