一简介
http-proxy-middleware用于后台将请求转发给其它服务器。
二 安装
1 $ npm install --save-dev http-proxy-middleware
三 使用
在src同级目录创建setupProxy.js如图所示
const { createProxyMiddleware } = require('http-proxy-middleware'); //注意写法,这是1.0以后的版本,最好按抄module.exports = function (app) {
app.use(createProxyMiddleware('/api',
{
target: 'http://ip:8000/',
pathRewrite: {
'^/api': '',
},
changeOrigin: true,
secure: false, // 是否验证证书
ws: true, // 启用websocket
}
));
};
以上表达的意思是,把/api 代理到 http://ip:8000/ 到这个网址上,重写一定要,如果不写
pathRewrite: {'^/api': '',
},
会异常,会直接代理到http://ip:8000/api上去了,不是我们要的结果
四 测试
handle_click = ()=>{let t = this;
fetch("/api/org/all", {method: 'GET'}).then(
function (res) {
console.log(res);
res.json().then(function (data) {
console.log(data);
t.setState({
news:data
});
}
)
});
};
其中/api/org/all 表达的网址的数据是
{
"total": 1,
"list": [{
"id": "64",
"name": "湖南长沙",
"code": "hncs",
"type": "试装"
}],
"pageNum": 1,
"pageSize": 10,
"size": 1,
"startRow": 1,
"endRow": 1,
"pages": 1,
"prePage": 0,
"nextPage": 0,
"isFirstPage": true,
"isLastPage": true,
"hasPreviousPage": false,
"hasNextPage": false,
"navigatePages": 8,
"navigatepageNums": [1],
"navigateFirstPage": 1,
"navigateLastPage": 1,
"firstPage": 1,
"lastPage": 1
}
完整代码。其中用到了antd mobile的东西,选择重要的看即可
import React, {Component} from 'react';import { Picker, List, WhiteSpace } from 'antd-mobile';
import { createForm } from 'rc-form';
const prjList = [
{
label: "柳州项目",
value: '1',
},
{
label: "南宁项目",
value: '2',
},
];
class Add extends React.Component {
state = {
prjList: [],
cols: 1,
pickerValue: [],
asyncValue: [],
visible: false,
colorValue: ['#00FF00'],
};
onChangeColor = (color) => {
this.setState({
colorValue: color,
});
};
handle_click = ()=>{
let t = this;
fetch("/api/org/all", {method: 'GET'}).then(
function (res) {
console.log(res);
res.json().then(function (data) {
console.log(data);
t.setState({
news:data
});
}
)
});
};
render() {
const { getFieldProps } = this.props.form;
return (<div>
<WhiteSpace size="lg" />
<List style={{ backgroundColor: 'white' }} className="picker-list">
<Picker
data={prjList}
value={this.state.colorValue}
cols={1}
onChange={this.onChangeColor}
>
<List.Item arrow="horizontal">选择项目</List.Item>
</Picker>
</List>
<WhiteSpace size="lg" />
<button onClick={this.handle_click}>button</button>
</div>);
}
}
const Wrapper = createForm()(Add);
export default class OrderAdd extends Component {
render() {
return (
<Wrapper />
)
}
}
还没有评论,来说两句吧...