react如何访问本地接口
访问本地接口的方法
在React中访问本地接口通常涉及开发环境配置和跨域问题处理。本地接口可能运行在本地开发服务器(如localhost:3000)或其他端口(如后端服务的localhost:8080)。
配置代理解决跨域问题
开发环境下,React应用可以通过配置代理将API请求转发到后端服务。在package.json中添加proxy字段:
{
"proxy": "http://localhost:8080"
}
这样所有未知请求会被自动转发到http://localhost:8080,无需处理跨域。
使用环境变量管理接口地址
创建.env.development文件定义开发环境变量:
REACT_APP_API_BASE_URL=http://localhost:8080/api
代码中通过process.env.REACT_APP_API_BASE_URL访问该变量:
fetch(`${process.env.REACT_APP_API_BASE_URL}/users`)
.then(response => response.json())
手动设置CORS头
如果后端服务支持,可以添加CORS头允许React应用访问:
// Express示例
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
使用axios发送请求
安装axios库后创建实例:
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:8080/api',
headers: { 'Content-Type': 'application/json' }
});
// 使用示例
api.get('/data').then(response => console.log(response.data));
开发服务器配置
通过setupProxy.js自定义代理规则(需安装http-proxy-middleware):
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8080',
changeOrigin: true,
})
);
};
生产环境配置
生产环境需确保接口地址指向实际部署的后端服务:
REACT_APP_API_BASE_URL=https://api.example.com
通过条件逻辑区分环境:
const baseURL = process.env.NODE_ENV === 'development'
? 'http://localhost:8080'
: 'https://api.example.com';






