×React - fetch('/')不会在Express.router中碰到索引路由

×React - fetch('/')不会在Express.router中碰到索引路由

问题描述:

我已经使用Express了一些,但是新到了React。我已经将React连接到可以正常工作的Express服务器,但在我的主React App组件中遇到问题fetch('/')可能会在我的Express应用程序中碰到索引路线。例如,我在Express中有这些路线:×React - fetch('/')不会在Express.router中碰到索引路由

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')或东西,但我想如果可能的话,以保持它作为('/')路线在快速应用。

如果有人能指出我做错了什么或者我可以尝试做什么,我会很感激。提前致谢!

+1

我不明白的是,您的前端应用程序如何服务?应用程序(我假设位于根目录)和您试图获取的数据的根目录之间没有冲突吗?甚至可能提取''/“'? – Jaxx

+0

React应用程序位于我的Express应用程序根目录下的一个名为'client'的文件夹中。我在我的React应用程序的package.json中使用''proxy':“http:// localhost:3001”''(这是我的Express应用程序托管的端口)。然后我运行'http:// localhost:3000'上的React应用程序并启动Express,只要我不使用''fetch('/')',一切正常。所以也许你碰到了一些东西......也许在React的根目录和我试图调用的快速路线之间存在冲突? – mikeym

+0

尝试删除该代理配置,而是执行'fetch(“http:// localhost:3001 /”)',看看它是否工作。是的,肯定存在冲突,imo。 – Jaxx

有了您的前端应用程序从http://localhost:3000被服务和后端数据API从http://localhost:3001服务,做一个fetch('/')将在http://localhost:3000请求数据。

'proxy'参数设置在您的前端package.json不会改变这一点。例如,该参数用于运行传出请求的节点应用程序,而不用于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}/`) 
... 
+0

更改为'fetch('http:// localhost:3001 /')'做了技巧谢谢。我唯一需要做的其他事情是在后端启用CORS。如果有人得到相同的错误,下面的代码应该解决这个问题。 'app.use(function(req,res,next){res.header(“Access-Control-Allow-Origin”,“*”); res。头(“Access-Control-Allow-Headers”,“Origin,X-Requested-With,Content-Type,Accept”); next(); });' – mikeym