[英]× React - fetch('/') won't hit index route in Express.router
我在 Express 方面做过一些工作,但我对 React 是新手。 我已经将 React 连接到一个可以工作的 Express 服务器,但是在我的主要 React App 组件中获取fetch('/')
以命中我的 Express 应用程序中的索引路由时遇到问题。 例如,我在 Express 中有这些路线:
app.use('/', routes);
app.use('/users', users);
两条路线在 Express 中是相同的。 他们对 MongoDB 进行了一个简单的调用,响应是res.json(data)
。 此外,当我在 Express 端口上测试这些路由时,它们都可以正常工作。
下面是我的 React 组件。 问题是当我尝试使用fetch('/')
来命中相应的app.use('/', routes);
在 Express 中它不起作用。 如果我将其更改为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
而您的后端数据 API 从http://localhost:3001
,执行fetch('/')
将在http://localhost:3000
请求数据http://localhost:3000
。
在前端package.json
设置'proxy'
参数不会改变这一点。 例如,此参数用于运行传出请求的节点应用程序,而不是 React 应用程序。
因此,要从前端检索后端数据,您必须执行fetch('http://localhost:3001/')
。 如果您想避免重复并为生产做准备,您可以在单独的文件中定义 API 基本 URI,即位于客户端源代码树根目录的config.js
文件:
// 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}/`)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.