axios数据交互
-
安装axios
cnpm i axios --save
2.发起http请求
this.axios.get('/api/menulist').then(res=>{ console.log(res); }) this.axios.post('/api/menuedit', {pid: '345sdfj'}).then(res=>{ console.log(res); })
-
配置代理之手动配置
-
安装http-proxy-middleware
cnpm i http-proxy-middleware --save
-
创建setupProxy.js文件
在src下创建文件【setupProxy.js】js
const { createProxyMiddleware }=require("http-proxy-middleware"); module.exports=(app)=>{ app.use(createProxyMiddleware('/api', { target: 'http://localhost:3000',/*这里写自己的代理地址*/ changeOrigin: true,//允许跨域 })); } npm start #重启项目
fetch
fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对 象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点 像jQuery ajax。但是,一定记住fetch不是ajax的进一步封装,而是原生js,没有使 用XMLHttpRequest对象。fetch有很多优势:
1语法简单,更加语义化。
2基于 标准Promise实现,支持async/await。
3提供了丰富的API
4脱离了XHR。fetch是 一种HTTP数据请求的方式,在react中,数据交互仍然使用axios
2-1.fetch之get请求
fetch('/api/menulist',{ headers:{ 'Content-Type':'application/x-www-form-urlencoded' } }).then(res=>{ return res.json(); }).then(res=>{ console.log(res); })
2-2.fetch之post请求
fetch('/api/menuedit',{ method:'POST',//post请求 headers:{ //请求头,不需要是可以不写使用默认值 'Content-Type