【问题标题】:× React - fetch('/') won't hit index route in Express.router× React - fetch('/') 不会命中 Express.router 中的索引路由
【发布时间】:2018-04-02 17:03:47
【问题描述】:

我在 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 应用中将其保留为 ('/') 路由。

如果有人能指出我做错了什么或我可以尝试的事情,我将不胜感激。提前致谢!

【问题讨论】:

  • 我不明白的是,你的前端App是怎么服务的?应用程序(我假设它位于根目录)与您尝试获取的数据的根位置之间是否存在冲突?获取"/" 甚至可能吗?
  • React 应用程序位于我的 Express 应用程序根目录中名为 client 的文件夹中。我在我的 React 应用程序的 package.json 中使用"proxy": "http://localhost:3001"(这是我的 Express 应用程序所在的端口)。然后我在http://localhost:3000 上运行React 应用程序并启动Express,只要我不使用fetch('/'),一切正常。所以也许你遇到了什么问题......也许 React 的根目录和我试图在 fetch 中调用的 Express 路由之间存在冲突??
  • 尝试删除该代理配置,然后执行fetch("http://localhost:3001/"),看看它是否有效。是的,肯定有冲突,imo。

标签: javascript node.js mongodb reactjs express


【解决方案1】:

由于您的前端应用由 http://localhost:3000 提供服务,而您的后端数据 api 由 http://localhost:3001 提供服务,因此执行 fetch('/') 将在 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}/`)
...

【讨论】:

  • 更改为 fetch('http://localhost:3001/') 成功了,谢谢。我唯一需要做的就是在我的后端启用 CORS。如果有人遇到同样的错误,下面的代码应该可以解决这个问题。 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-14
相关资源
最近更新 更多