簡體   English   中英

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

[英]× 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM