umi 框架如何实现跨域请求?
warning:
这篇文章距离上次修改已过188天,其中的内容可能已经有所变动。
在 Umi 框架中实现跨域请求,通常有以下几种方法:
配置代理(推荐方式):
在 Umi 项目的
.umirc.ts
或config/config.ts
文件中配置代理规则,将跨域请求代理到本地服务器。
export default {
proxy: {
'/api': {
target: 'http://api.example.com',
changeOrigin: true,
pathRewrite: { '^/api': '' },
},
// 可以配置多个代理规则
},
};
使用 webpack-dev-server 的代理:
如果你使用的是 webpack 作为构建工具,可以在
webpack.config.js
中配置 devServer.proxy 来实现跨域请求的代理。
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://api.example.com',
changeOrigin: true,
pathRewrite: { '^/api': '' },
},
},
},
};
使用 axios 的代理配置:
如果跨域请求是动态发起的,可以在发起请求时配置 axios 的代理。
const instance = axios.create({
baseURL: '/api', // 代理后的地址
});
instance.get('/somePath').then(response => {
// handle response
});
使用 cors 代理服务:
设置一个中间的代理服务器来处理跨域请求,例如使用
https://cors-anywhere.herokuapp.com/
。
fetch('https://cors-anywhere.herokuapp.com/http://api.example.com/somePath')
.then(response => response.json())
.then(data => console.log(data));
以上方法中,第一种配置代理的方式是最为推荐的,因为它可以直接在开发环境中解决跨域问题,无需更改生产环境的服务器设置。在实际部署时,通常需要在服务器端设置合适的 CORS 策略来允许跨域请求。
评论已关闭