react如何配置正式地址
配置生产环境地址
在React项目中配置正式地址通常涉及环境变量的设置、API基础URL的配置以及构建优化。以下是具体方法:
设置环境变量
创建.env.production文件,定义生产环境变量:
REACT_APP_API_BASE_URL=https://api.production.com
REACT_APP_ENV=production
动态配置API地址 在API请求模块中使用环境变量:
const apiClient = axios.create({
baseURL: process.env.REACT_APP_API_BASE_URL
});
构建生产版本 运行构建命令生成优化后的代码:
npm run build
部署配置
针对不同部署环境,需要调整服务器配置和路由处理:
Nginx服务器配置

server {
listen 80;
server_name yourdomain.com;
root /path/to/react/build;
index index.html;
location / {
try_files $uri /index.html;
}
}
CDN配置
在构建后上传静态文件至CDN,修改public/index.html中的资源路径:
<script src="https://cdn.yourdomain.com/static/js/main.js"></script>
环境检测与切换
实现运行时环境检测可增强灵活性:
环境检测函数
const getApiBaseUrl = () => {
if (window.location.hostname === 'localhost') {
return process.env.REACT_APP_DEV_API_URL;
}
return process.env.REACT_APP_API_BASE_URL;
};
多环境配置文件
创建config.js根据不同环境导出配置:

export default {
production: {
apiUrl: 'https://api.prod.com'
},
staging: {
apiUrl: 'https://api.stage.com'
}
};
安全注意事项
生产环境配置需考虑以下安全实践:
敏感信息保护 确保敏感数据不直接存储在前端代码中,通过后端接口获取
HTTPS强制
配置服务器强制使用HTTPS,在.htaccess中添加:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
CSP策略 在HTTP头中设置内容安全策略:
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'





