我在Express上工作了一段时间,但对React还是很陌生。我已经将React连接到可以运行的Express服务器,但是在获取我的主要React App组件中的fetch('/')
来打我Express应用中的索引路由时遇到问题。例如,我在Express中有以下路线:
app.use('/', routes);
app.use('/users', users);
两条路线在Express中相同。他们对MongoDB进行了简单的调用,响应为
res.json(data)
。同样,当我在Express端口上测试这些路由时,它们都可以正常工作。以下是我的React组件。问题是,当我尝试使用
fetch('/')
在Express中打相应的app.use('/', routes);
时,它不起作用。如果我将其更改为fetch('/users')
,它将起作用。import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {users: []}
componentDidMount() {
fetch('/') // this route doesn't work with Express!
.then(res => res.json())
.then(users => this.setState({ users }));
}
render() {
return (
<div className="App">
<h1>Users</h1>
{this.state.users.map(user =>
<div key={user.id}>{user.username}</div>
)}
</div>
);
}
}
export default App;
当然,我可以将索引路由名称更改为
('/index')
或其他名称,但我希望尽可能在Express应用中将其保留为('/')
路由。如果有人能指出我做错了什么或我可以尝试的事情,我将不胜感激。提前致谢!
最佳答案
通过http://localhost:3000
提供您的前端应用程序,并通过http://localhost:3001
提供您的后端数据api,执行fetch('/')
将在http://localhost:3000
上请求数据。
在前端'proxy'
中设置package.json
参数不会改变这一点。例如,此参数用于运行传出请求的节点应用程序,而不用于React应用程序。
因此,要从前端检索后端数据,必须执行fetch('http://localhost:3001/')
。如果您想避免重复并准备进行生产,则可以在单独的文件(即位于客户端源代码树的根目录中的config.js
文件)中定义API基本URI:
// general config goes here
const configGlob = {};
// production specific config goes here
const configProd = {
API_URI: "http://www.example.com/api/v2"
};
// development specific config goes here
const configDev = {
API_URI: "http://localhost:3001"
};
// merged config
const config = { ...configGlob, process.env.NODE_ENV === 'production' ? ...configProd : ...configDev };
export default config;
然后在你的
App.js
中:import config from './config';
...
fetch(`${config.API_URI}/`)
...