使用creat-react-app构建的项目,前后端的接口联调,对于端口proxy设置、网络请求axios插件的使用以及fetch 插件的使用
1、proxy设置
可以直接在package.json下配置,具体如下
"proxy": "域名"
2、axios插件的使用
使用npm下载插件
npm install axios --save
axios的使用,其中header是默认application/json;charset=utf-8。
import React, { Component } from 'react';
import axios from 'axios';
class Test extends Component {
constructor (props) {
super(props)
}
getaxiosPost () {
axios({
method:'post',
url:'/api/excel/web/list',
data:{
type:"import",
page:1,
pageSize:10
},
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function(res){
console.log(res.data);
}).catch(function(error){
console.log(error);
});
}
getaxiosGet () {
axios({
method:'get',
url:'/api/excel/web/status/disable/2',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function(res){
console.log(res.data);
}).catch(function(error){
console.log(error);
});
}
render() {
return (
search:{this.props.location.search}
state:{this.props.location.state.mold}
axios的post请求
axios的get请求
this.props.history.goBack()}>返回上一页
);
}
}
export default Test;
3、fetch 插件的使用
安装 whatwg-fetch、es6-promise
npm install whatwg-fetch es6-promise --save
fetch代码的封装:http.js
import 'whatwg-fetch'
import 'es6-promise'
//将json对象拼接成 key=val&key=val 的字符串形式
function obj2params(obj) {
var result = '';
var item;
for(item in obj){
result += '&' + item + '=' +encodeURIComponent(obj[item]);
}
if(result) {
result = result.slice(1);
}
return result;
}
export function postGpio(url,param) {
var result = fetch(url, {
method: 'post',
mode:'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: obj2params(param)
});
return result;
}
export function getGpio(url,param) {
var result = fetch(url, {
credentails: 'include',
mode: "cors",
header: {
"Content-Type": "json"
},
});
return result;
}
fetch使用,请求
import React, { Component } from 'react';
import {getGpio,postGpio} from "../http";
class Test extends Component {
constructor (props) {
super(props)
}
getFetchPost () {
const result = postGpio('/api/excel/web/list',{
type:"import",
page:1,
pageSize:10
});
result.then(res => {
return res.json()
console.log(res,19)
}).then(json => {
// get result
const data = json
console.log(data,22)
}).catch(ex => {
// 发生错误
console.error('获取数据出错, ', ex.message)
})
}
getFetchGet () {
const result = getGpio('/api/excel/web/status/disable/2');
result.then(res => {
return res.json()
console.log(res,19)
}).then(json => {
// get result
const data = json
console.log(data,22)
}).catch(ex => {
// 发生错误
console.error('获取数据出错, ', ex.message)
})
}
render() {
return (
search:{this.props.location.search}
state:{this.props.location.state.mold}
axios的post请求
axios的get请求
this.props.history.goBack()}>返回上一页
);
}
}
export default Test;
参考文献:1、https://blog.csdn.net/hopefullman/article/details/79106112
2、https://blog.csdn.net/qq_29854831/article/details/79456106