axios的简单封装即使用

(一)安装

使用npm安装

$ npm install axios

使用yarn安装

$ yarn add axios 

(二) 安装完成以后创建一个request的js文件,将axios和qs引入。

import axios from "axios"
import qs from "qs"
export function request(config) {
	const instance = axios.create({
		baseURL: 'https://localhost:44335/api/Home',
		timeout: 5000,
	})
	console.log(config.data)
	//判断是否用data传值
	if (config.data == undefined) {

	} else {
		// data传值要使用格式
		// config.data=qs.stringify(config.data)
		// config.data=JSON.stringify(config.data)
	}
	//判断网络请求是否为空
	if (config.method == undefined) {
		//为空默认GET请求
	} else {
		config.method = config.method;
	}
	//请求拦截器
	instance.interceptors.request.use(config => {
		return config;
	}, err => {
		console.log(config.method + "请求失败")
	})
	//响应拦截器
	instance.interceptors.response.use(res => {
		return res.data;
	}, err => {
		console.log(config.method + "响应失败")
	})

	return instance(config)

}

(三)因为这里的 baseURL并不是完整的url路径,很多开发当中前面的路径是一致的,后面会因为开发的业务不一样,而改变,现在需要在创建一个关于你业务的专用js文件,用于传输config,我们需要将前面这个request引入。

import {
	request
} from 'e:/.net/Web-Api-2-1/Web-Api-2-1/src/nwork/request.js'
export function postGG(a) {
	return request({
		method: 'post',
		url: '/GG',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8 '
		},
		params: {

		},
		data: a
	})
}

这里的url会和前面的 baseURL自动配对形成完整的一个url地址,这里使用的post请求,因为这里的a传输的是一个FormData对象,所以自定义请求头headers使用的是'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8 '。(完整路径:https://localhost:44335/api/Home/GG)

里面还有一些其他的参数,根据你的业务来决定如:

params是与请求一起发送的 URL 参数,必须是一个简单对象或 URLSearchParams 对象.

data是作为请求体被发送的数据,仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法.

 transformRequest允许在向服务器发送前,修改请求数据,它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法

transformResponse在传递给 then/catch 前,允许修改响应数据

(四)使用我们封装的方法

 我们需要将postGG()方法进行引用

import {
		postGG
	} from '../../nwork/amain.js'

 这里我创建了一个点击事件onfile(),在点击后会触发我们引用的postGG()方法进行网路请求,该方法将a传输到后端,即完成了网络请求。

methods: {
	onfile() {
		let a = new FormData();
		postGG(a).then(res => {
			console.log(res)
		}).catch(err => {
			console.log(err)
		})
	}
},

 

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值