react项目前后端分离部署
2026-05-02 12:25:25
209
分类:Web前端
react 通过 http-proxy-middleware 实现跨域请求
安装 http-proxy-middleware 模块
在 src 文件夹下 创建 setupProxy.js 文件
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(createProxyMiddleware('/api', {
target: 'http://***',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
},
}));
};http-proxy-middleware 只在开发模式有效,生产环境需要在服务器配置代理
一、react项目部署在apache
需要在根目录创建创建.htaccess文件,配置内容如下
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . index.html [L]apache跨域代理
通过反向代理实现
<VirtualHost *:80> DocumentRoot "***" ServerName ***.com ServerAlias *** <Directory "***"> Options FollowSymLinks ExecCGI AllowOverride All Order allow,deny Allow from all Require all granted DirectoryIndex index.php index.html error/index.html </Directory> ProxyRequests Off <Proxy /api> Order deny,allow Allow from all </Proxy> ProxyPass /api http://*** ProxyPassReverse /api http://*** </VirtualHost>
二、react项目部署在nginx
nginx配置如下
server {
listen 80;
server_name localhost;
access_log off;
#access_log logs/host.access.log main;
#打包
location ^~/ {
root ***;
try_files $uri /index.html;
}
#后台代理,注意后面有/
location ^~/api/{
#本地
#proxy_pass http://***;
#测试环境
proxy_pass http://***;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}