在React中使用axios发送请求

it2026-04-24  2

其实React和vue 中 发送请求的方式 差不多。

VUE中: import Vue from ‘vue’

Vue.prototype.$http = axios 挂载到原型上供其他页面方便使用

React中:

将axios 挂载到React 上的步骤:

cnpm i axios -S

import axios from ‘axios’

挂载axios之前,配置transformRequest 在挂载axios之前, 全局配置一下 transformRequest 参数。 (这个是为了让我们在使用axios中的post传参数的时候,不用那么麻烦的使用查询字符串(例如name=zs&age=18)

transformRequest 作用:就是在发起Post 请求之前, 对要发送给服务器的数据,做一层包装转换

axios.defaults.transformRequest = [function(data,headers){ //function中的 data 就是要发送给服务器的数据 //**在这里,我们要想办法,把 data 从 对象 {name: zs ,age: 22 } 转成 查询字符串 name=zs&age=22** const arr = [ ] for(let key in data){ arr.push(key + '=' +date[key]) } return arr.join('&') }]

//设置全局的baseURL

axios.defaults.baseURL = 'http://39.106.32.91:3000'

将axios挂载到父类的 原型上 (那么只要子类继承了父类,子类就可用父类身上的东西) index.js上进行引用

React.component.prototype.$http = axios

在页面上发起get请求:

getInfo = () =>{ this.$http('http://39.106.32.91:3000/api/getlunbo').then(result=>{ console.log(result.data) }) }

使用 ES7 的async 和 await 来优化 Promise的调用

getInfo = async ()=>{ const {data} = await this.$http('http://39.106.32.91:3000/api/getlunbo') console.log(data) }

在页面上发起 post请求:

注意:在Ajax发起Post请求的时候,如果没有 指定Content-Type, 则默认 为 text/plain; charset=utf-8(字符串型的)

//一般情况下, 服务器认为 客户端Ajax发送的数据类型是application/x-www-form-urlencoded

//form表单元素,默认有属性 enctype = “application/x-www-form-urlencoded”

在没有使用Axios的transformRequest的情况下,传对象是不行的,(下面这种代码方式不可!!!)

postInfo = () =>{ this.$http.post('http://39.106.32.91:3000/api/post'(//要发送的地址), { name :"zs", age:22 (//要传的参数) }, { headers :{'Content-Type':'application/x-www-form-urlencoded'} (//config配置参数) } ) }.then(res=>{ })

标准格式 post 的

如果要发起Post请求,同时给服务器提交参数,则提交给服务器的数据,不能写成对象,需要自己给参数拼接成查询字符串

postInfo = () =>{ this.$http.post('http://39.106.32.91:3000/api/post'(//要发送的地址),‘name=zs&age=22’ )}.then(res=>{ })

post每次给传给服务器的参数,拼接成查询字符串太麻烦了! 所以我们优化一下写用到axios的transformRequest

用到axios中的 transformRequest 在挂载axios之前, 全局配置一下 transformRequest 参数即可。 在挂载axios之前, 全局配置一下 transformRequest 参数 (这个是为了让我们在使用axios中的post传参数的时候,不用那么麻烦的使用查询字符串) transformRequest 的作用: 就是在发起Post 请求之前, 对要发送给服务器的数据,做一层包装转换

axios.defaults.transformRequest = [function(data,headers){ //function中的 data 就是要发送给服务器的数据 //在这里,我们要想办法,把 data 从 对象 {name: zs ,age: 22 } 转成 查询字符串 name=zs&age=22 const arr = [ ] for(let key in data){ arr.push(key + '=' +date[key]) } return arr.join('&') }] //也可以用es6的方式进行拼接 const arr = [ ] for(let key in data){ //arr.push(key + '=' +date[key]) arr.push(`${key} = ${data[key] }`) } return arr.join('&') }]

这样转换完之后, 我们在每次发送post请求的时候,直接发对象就不会出错了。。。

最新回复(0)