简体   繁体   English

× React - fetch('/') 不会命中 Express.router 中的索引路由

[英]× React - fetch('/') won't hit index route in Express.router

I've worked a bit with Express but am new-ish to React.我在 Express 方面做过一些工作,但我对 React 是新手。 I have React already hooked up to an Express server that works but having a problem getting fetch('/') in my main React App component to hit the index route in my Express app.我已经将 React 连接到一个可以工作的 Express 服务器,但是在我的主要 React App 组件中获取fetch('/')以命中我的 Express 应用程序中的索引路由时遇到问题。 For example I have these route in Express:例如,我在 Express 中有这些路线:

app.use('/', routes);
app.use('/users', users);

Both routes are identical in Express.两条路线在 Express 中是相同的。 They make a simple call to MongoDB and the response is res.json(data) .他们对 MongoDB 进行了一个简单的调用,响应是res.json(data) Also when I test these routes pure on the Express port they both work fine.此外,当我在 Express 端口上测试这些路由时,它们都可以正常工作。

Below is my React component.下面是我的 React 组件。 The problem is when I try to use fetch('/') to hit the corresponding app.use('/', routes);问题是当我尝试使用fetch('/')来命中相应的app.use('/', routes); in Express it doesn't work.在 Express 中它不起作用。 If I change it to fetch('/users') it works.如果我将其更改为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;

Of course I could change the index route name to ('/index') or something but I'd like to keep it as ('/') route in the Express app if at all possible.当然,我可以将索引路由名称更改为('/index')或其他名称,但如果可能的话,我想在 Express 应用程序中将其保留为('/')路由。

If anyone can point out what I am doing wrong or things I can try I'd be grateful.如果有人能指出我做错了什么或我可以尝试的事情,我将不胜感激。 Thanks in advance!提前致谢!

With your front-end app being served from http://localhost:3000 and your back-end data api served from http://localhost:3001 , doing a fetch('/') will request data at http://localhost:3000 .您的前端应用程序从http://localhost:3000而您的后端数据 API 从http://localhost:3001 ,执行fetch('/')将在http://localhost:3000请求数据http://localhost:3000

Having the 'proxy' param set in your front-end package.json will NOT change that.在前端package.json设置'proxy'参数不会改变这一点。 This param is used, for instance, for node apps running outgoing requests, not for a React app.例如,此参数用于运行传出请求的节点应用程序,而不是 React 应用程序。

So to retrieve your back-end data from the front-end, you have to do a fetch('http://localhost:3001/') .因此,要从前端检索后端数据,您必须执行fetch('http://localhost:3001/') If you want to avoid repetition, and to prepare for production, you could define your API base URI in a separate file, ie a config.js file located at the root of your client source tree:如果您想避免重复并为生产做准备,您可以在单独的文件中定义 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;

And then in your App.js :然后在你的App.js

import config from './config';
...
fetch(`${config.API_URI}/`)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM