我想在本地网络上托管一个react服务器和一个node服务器,该网站有多个页面并使用axios从node服务器发送和接收数据,在package.json中有一个代理来引导react到node服务器
"proxy": "http://localhost:8080",
"homepage": "./"
ps:如果重要的话我使用express.js
确保它在特定端口上运行,例如端口 8080
const express = require('express');
const app = express();
const port = 8080;
// Define your routes and middleware here
app.listen(port, () => {
console.log(`Node server is running on port ${port}`);
});
现在你的 React 应用程序已经在 package.json 文件中配置了“代理”字段,这很好
使用以下命令运行你的 React 开发服务器:
npm start
默认情况下,它应该在端口 3000 上运行。
现在访问本地反应
通过查找本地 IP 地址并指定端口(通常为 3000),从同一本地网络上的其他设备访问您的 React 应用程序:
从同一网络上的另一台设备查找您的本地 IP 地址,打开网络浏览器并输入
http://your-local-ip:3000.
现在可以在本地服务器上访问它
不轮流进行api请求
在您的 React 应用程序中,使用
axios
或任何其他 HTTP 客户端,使用代理中定义的相对路径向您的 Node 服务器发出 API 请求。
例如,如果您的 Node 服务器中有这样的路由
app.get('/api/data', (req, res) => {
// Handle the API request here
});
您可以像这样从 React 应用程序发出请求
axios.get('/api/data')
.then(response => {
// Handle the response data
})
.catch(error => {
// Handle errors
});
package.json
中的代理配置会自动将请求路由到http://localhost:8080/api/data
现在你的 React 应用程序和 Node 服务器应该在你的本地网络上协同工作。