代理
一. 简介
代理也称网络代理,是一种特殊的网络服务,允许一个终端(一般为客户端)通过这个服务与另一个终端(一般为服务器)进行非直接的连接。
dev: {
'/api/': {
target: 'https://proapi.azurewebsites.net',
changeOrigin: true,
pathRewrite: { '^': '' },
},
},
上述配置表示,将 /api 前缀的请求,代理到 http://jsonplaceholder.typicode.com/,替换请求地址中的/api 为 ‘’,并且将请求来源修改为目标url。如请求 /api/a,实际上是请求
http://jsonplaceholder.typicode.com/a。
二. 使用
1. 应用场景
一般我们使用这个能力来解开发中的跨域访问问题。由于浏览器(或者 webview)存在同源策略,之前我们会让服务端配合使用
Cross-Origin Resource Sharing (CORS) 策略来绕过跨域访问问题。现在有了本地的 node服务,我们就可以使用代理来解决这个问题。
2. 应用原理
原理其实很简单,就是浏览器上有跨域问题,但是服务端没有跨域问题。我们请求同源的本地服务,然后让本地服务去请求非同源的远程服务。需要注意的是,请求代理,代理的是请求的服务,不会直接修改发起的请求
url。它只是将目标服务器返回的数据传递到前端。所以你在浏览器上看到的请求地址还是 http://localhost:8000/api/a。
3. 注意事项
值得注意的是 proxy暂时只能解开发时(dev)的跨域访问问题,可以在部署时使用同源部署。如果在生产上(build)的发生跨域问题的话,可以将类似的配置转移到 Nginx 容器上。
三. 实战
1. 配置代理
1.proxy.ts配置
在config文件夹下的proxy.ts下添加添加代理配置,默认格式已有,只需修改target中的ip(后端地址),其他的参数可根据具体需要修改
/**
* @name 代理的配置
* @see 在生产环境 代理是无法生效的,所以这里没有生产环境的配置
* -------------------------------
* The agent cannot take effect in the production environment
* so there is no configuration of the production environment
* For details, please see
* https://pro.ant.design/docs/deploy
*
* @doc https://umijs.org/docs/guides/proxy
*/
export default {
dev: {
// localhost:8000/api/** -> https://preview.pro.ant.design/api/**
'/api/': {
// 要代理的地址
target: 'http://127.0.0.1:8080',
// 配置了这个可以从 http 代理到 https
// 依赖 origin 的功能可能需要这个,比如 cookie
changeOrigin: true,
// pathRewrite: { '^/api/': '' },
},
},
/**
* @name 详细的代理配置
* @doc https://github.com/chimurai/http-proxy-middleware
*/
test: {
'/api/': {
target: 'https://proapi.azurewebsites.net',
changeOrigin: true,
pathRewrite: { '^': '' },
},
},
pre: {
'/api/': {
target: 'your pre url',
changeOrigin: true,
pathRewrite: { '^': '' },
},
},
};
2.config.ts配置
默认自动引入dev中的配置
// https://umijs.org/config/
import { defineConfig } from '@umijs/max';
import { join } from 'path';
import defaultSettings from './defaultSettings';
import proxy from './proxy';
import routes from './routes';
const { REACT_APP_ENV } = process.env;
export default defineConfig({
/**
* @name 代理配置
* @description 可以让你的本地服务器代理到你的服务器上,这样你就可以访问服务器的数据了
* @see 要注意以下 代理只能在本地开发时使用,build 之后就无法使用了。
* @doc 代理介绍 https://umijs.org/docs/guides/proxy
* @doc 代理配置 https://umijs.org/docs/api/config#proxy
*/
proxy: proxy[REACT_APP_ENV || 'dev'],
});
2. 前端
1.前端页面
在page下创建Team组件,然会在Team组件中编写index.txs
import { MenuOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { useState,useEffect } from 'react';
import { SortableHandle } from 'react-sortable-hoc';
import { getTeamList} from '@/services/ant-design-pro/team';
import {
ProTable,
ProFormText,
QueryFilter,
} from '@ant-design/pro-components';
const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);
let message: any;
const columns: ProColumns[] = [
{
title: '排序',
dataIndex: 'sort',
width: 60,
className: 'drag-visible',
render: () => <DragHandle />,
},
{
title: 'Name',
dataIndex: 'name',
className: 'drag-visible',
},
{
title: 'Phone',
dataIndex: 'phone',
},
{
title: 'Email',
dataIndex: 'email',
},
];
export default () => {
const [list, setData] = useState([]);
const handleClick=async(props:any)=>{
console.log("获取前端参数")
console.log(props)
const respone = await getTeamList(props)
console.log("获取后台数据")
console.log(respone.data)
if(respone.status='200'){
setData(respone.data);
}else{
setData(data);
}
console.log(message)
}
//
useEffect(()=>{
handleClick(data);
},[])
return (
<div>
<QueryFilter<{
name: string;
age: string;
address: string;
}>
onFinish={async (values) => {
handleClick(values);
console.log(values.age);
}}
>
<ProFormText name="name" label="姓名" />
<ProFormText name="phone" label="手机号" />
<ProFormText name="email" label="Email" />
</QueryFilter>
<ProTable
headerTitle="拖拽排序"
columns={columns}
search={false}
rowKey="index"
pagination={false}
dataSource={list}
/>
</div>
);
};
2.请求api
在service文件夹下创建team.ts,这里是存放前端请求的地方
// @ts-ignore
/* eslint-disable */
import { request } from '@umijs/max';
/** 获取team列表 post /api/team/teamList */
export async function getTeamList(options?: { [key: string]: any }) {
return request(' /api/team/teamList', {
method: 'POST',
...(options || {}),
});
}
3.后端
1.配置文件
在yaml文件中配置端口号,默认8080`
server:
port: 8080
2.后端接口
- 创建实体
@Data
public class TeamVo {
private String id;
private String name;
private String phone;
private String email;
}
- 创建接口
@Slf4j
@RestController
@RequestMapping("/api/team")
public class TeamController {
@PostMapping("/teamList")
public SingleResponse<List<NoticeVo>> getAlarmNoticeList(String name,String age,String address){
List<TeamVo > noticeVos = new ArrayList<>();
TeamVo noticeVo = new TeamVo ();
noticeVo.setId("1");
noticeVo.setName("黑白");
noticeVo.setPhone("187****6124");
noticeVo.setEmail("hb@alibaba-icn.com");
noticeVos.add(noticeVo);
TeamVo noticeVo2 = new TeamVo ();
noticeVo2.setId("2");
noticeVo2.setName("无常");
noticeVo2.setPhone("137****8615");
noticeVo2.setEmail("wc@alibaba-icn.com");
noticeVos.add(noticeVo2);
TeamVo noticeVo3 = new TeamVo ();
noticeVo3.setId("3");
noticeVo3.setName("艾大风");
noticeVo3.setPhone("155****6251");
noticeVo3.setEmail("aidafeng@alibaba-icn.com");
noticeVos.add(noticeVo3);
return SingleResponse.buildSuccess(noticeVos);
}
}
这里面的 SingleRespons根据自己的需求和约定个数据结构进行封装,这里不做介绍
4. 结果呈现



3145

被折叠的 条评论
为什么被折叠?



