React异步请求

1.axios异步请求

基本语法

axios({
	url: 请求地址,
	method:请求方式,
	data: {POST参数},
	params: {GET参数},
	headers: {请求头}
}).then(response=>{
	console.log(response服务器返回数据)
})

axios.get(url,{params:{get参数}}.then(response=>处理服务器返回数据))
axios.post(url,{post参数}).then(response=>处理服务器返回数据)

axios底层式怎么实现的

通过封装异步对象XMLHttpRequest、通过Promise的方式解决了异步调用的返回值问题,提供了便捷的操作函数,可以通过配置的方式调用,也可以通过提供的快捷函数直接发送请求完成数据异步请求

项目中安装axios

yarn add axios

2.axios封装

创建axios.js

import axios from "axios"
const instance = axios.create({
	baseURL: "/api"
})
instance.interceptors.request.use(request=>{
	return request
})
instance.interceptors.response.use(response=>{
	return response.data
})
Component.proptotype.$axios = instance
export default instance

在index.js中引入封装的代码,让封装的axios生效

import './utile/axios'

3.fetch异步请求

fetch有抓取的意思,是浏览器封装的API,主要在新版浏览器中使用
基本语法:发送get请求

fetch("url").then(response=>response.json()).then(ret=>console.log('获取到服务器返回的数据',ret))

基本语法:发送POST请求

fetch("url",{method:"POST",headers:{'Content-Type':'application/json'}},body:JSON.stringify({'username':'admin',"password":"123456"})).then(reponse=>response.json()).then(ret=>console.log("获取到POST请求结果",ret))

基本语法:上传文件

let formData = new FormData() 
formData.append("name","zhangsan")
formData.append("avatar",inputRef.files[0])
fetch('url',{
	method:"POST",
	body:formData
}).then(response=>response.json()).then(ret=>console.log("文件上传服务器返回的结果消息",ret))

5.fetch封装

//request可以发送GET、POST请求,默认发送GET请求,可以附带自定义请求头和请求体数据
function request(url,method="GET",header={},body={}){
	const options = {
		method.
		headers:Object.assign({
			"Content-Type": "application/json"
		},headers)
	}
	if(method === "POST") {
		options.body = JSON.stringfy(body)
	}
	return fetch(url,options).then(response=>response.json())
}
export default request

调用

request("/api/login","POST",_,{username:'zhangsan',password:'123456'}).then(ret=>alert('登录成功'))
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值