config.ts 中proxy的配置如下
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/api': '/api',
},
},
}
service.ts中某个方法如下
export async function queryRule(params: TableListParams) {
return request('/api/rule', {
params,
});
}
开发时在IDEA中直接 npm run start:no-mock 启动时,可以跨域访问到 本机 8080端口上的接口。
build之后将dist文件夹内生成的文件拷贝到springboot工程中 resources/static文件夹下,在8000端口启动springboot后,在浏览器端访问 index.html时,接口 /api/rule 报 404 。这个问题困扰了我很久,折腾了很多方法,都没用。没办法在仔细看一遍文档,
在https://pro.ant.design/docs/faq-cn中找到这句话:
注意:build 之后 proxy 无效,不要在 proxy 中配置请求
http://localhost:8001/api/users
,而是要在 http 请求的时候,直接访问该地址。如在src/utils/request.ts
中统一添加请求前缀。
哦,原来如此,改一下:
const host = 'http://localhost:8080';
export async function queryRule(params: TableListParams) {
return request(host + '/api/rule', {
params,
});
}
在重试,404消失,可以访问到8080端口上的接口了,问题解决。
不过接口需要支持跨域访问,后端使用的同样是springboot,需要加上 addCorsMappings 方法支持跨域。