在前后端分離的分布式架構中,跨域是一道無法繞過去的門檻,眾所周知,生產環境上解決跨域最便捷的方式是使用Nginx來處理,那么,在本地開發環境又該如何處理呢?
React框架里處理跨域問題,可以使用http-proxy-middleware庫解決。
http-proxy-middleware可實現全局設置,將客戶端請求轉發到目標服務器,從而實現代理服務器功能,進而解決模塊化前端跨域訪問的問題。
本文基於SpringBoot+React環境進行說明。
1.前端下載依賴
1 $ npm install --save-dev http-proxy-middleware
2.在src目錄下新建setupProxy.js文件
1 const { createProxyMiddleware } = require('http-proxy-middleware'); 2 module.exports = function(app) { 3 // /api 表示代理路徑 4 //target 表示目標服務器的地址 5 app.use( 6 '/api/system', 7 createProxyMiddleware({ 8 // http://localhost:4000/ 地址只是示例,實際地址以項目為准 9 target: 'http://127.0.0.1:8081', 10 // 跨域時一般都設置該值 為 true 11 changeOrigin: true, 12 // 重寫接口路由 13 // pathRewrite: { 14 // '^/admin': '',// 這樣處理后,最終得到的接口路徑為: http://localhost:8080/xxx 15 // } 16 }) 17 ); 18 19 app.use( 20 '/admin/example', 21 createProxyMiddleware({ 22 target: 'http://127.0.0.1:8080', 23 changeOrigin: true, 24 }) 25 ); 26 }
這里需要注意一點是,在http-proxy-middleware的1.0.0之前的版本與之后的版本,兩者對模塊引引用是存在差別的,如:
0.x.x版本的引用方式是:
1 const proxy=require('http-proxy-middleware');
1.0.0之后的版本引用方式:
1 const {createProxyMiddleware}=require('http-proxy-middleware');
該前端對應的后端設置如下:
1 server: 2 port: 8081 3 servlet: 4 context-path: /api 5
按照以上設置,即可實現本地開發環境解決跨域問題,當然,這里只適合在開發環境進行開發時設置,若發布到生產上后,最好方式是通過nginx代理來進行解決跨域問題。