【问题标题】:How do i access express.js routes from react.js client我如何从 react.js 客户端访问 express.js 路由
【发布时间】:2025-12-02 03:00:02
【问题描述】:

我正在尝试从 react 前端访问 express.js 路由,但我似乎不知道如何去做。我的 express.js 后端在 localhost:9000 上运行,而我的 react 前端在 localhost:3000 上运行。这是我的反应代码;

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: "" };
}

callAPI() {
    fetch("http://localhost:9000/:username")
        .then(res => res.text())
        .then(res => this.setState({ apiResponse: res }));
}

componentWillMount() {
    this.callAPI();
}


render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

    </div>
  );
}
}

export default App;

我在 express routes 文件夹中创建了两个文件,一个是 testAPI.js,另一个是 be.js。当我尝试在不使用反应的情况下从浏览器访问这两个文件中的任何一个时,可以说 localhost:9000/testAPI 它工作正常。但是当我尝试访问通过反应调用同一文件的 localhost:3000/testAPI 时,它给了我这个混乱的错误页面:

 <!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Not Found</h1><h2>404</h2><pre>NotFoundError: Not Found at C:\Users\Denoh\full\api\app.js:33:8 at Layer.handle [as handle_request] (C:\Users\Denoh\full\api\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:317:13) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:275:10) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:635:15 at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:260:14) at Function.handle (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:174:3) at router (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:47:12)</pre></body></html>

请帮忙

【问题讨论】:

    标签: reactjs express


    【解决方案1】:

    你需要在package.json中使用proxy来实现这个

    基本上你也设置了你想要代理的 url,以便 React 知道如何连接到你的服务器

    更多信息请参见:https://create-react-app.dev/docs/proxying-api-requests-in-development/

    【讨论】: