从 React 获取 API 向我发送错误的 URL

cra*_*eer 2 api node.js reactjs fetch-api

学习 React.js 和 Node.js,并使用后端的 Express API 和前端的 React.js 制作一个简单的 CRUD 应用程序。我的 React.js 的 App.js 看起来像这样。

    `import React, { Component } from 'react';
     import './App.css';
     import Rentals from './components/Rentals';
     import Idpage from './components/Idpage';

     import {
      BrowserRouter as Router,
      Route,
      Link
     } from 'react-router-dom';

   class App extends Component {

   render() {
    return (
    <div className="mainappdiv">
     <Router>
          <main>
            <Route exact path="/" component={Home} />
            <Route exact path="/rentals" component={Rentals} />
            <Route path="/rentals/:propertyid" component={Idpage} />
          </main>             
        </div>           
    </Router>
  </div>
      );
     }}

 export default App;
Run Code Online (Sandbox Code Playgroud)

我正在制作一个应用程序,当您访问 /rentals 时,它会获取数据并打印内容。目前正在运行,并且我的数据库中的所有数据正在呈现。
现在我尝试访问 /rentals/1 或 /rentals/2,然后尝试仅打印该 id 的列表。

   import React, { Component } from 'react';

   class Idpage extends Component {

   componentDidMount() {
    fetch('api/listofrentals/2')
        .then((response)=>{
            console.log(response)
            return response.json()
        })
        .then((singlerent)=>{
            console.log(singlerent)
        })
}


render() {
    return (
        <div>
            <p>this is the id page solo</p>
            <p>{this.props.match.params.propertyid}</p>
        </div>

    );
}}

   export default Idpage;
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我收到一条错误消息,说GET http://localhost:3000/rentals/api/listofrentals/2 404 (Not Found) 我正在尝试从 URL 中获取数据http://localhost:3000/api/listofrentals/2,但不明白为什么“rentals”部分位于 URL 中。我的 React 服务器在 localhost:3000 上运行,node.js 在 localhost:30001 上运行。我的 React 的 package.json 有这个"proxy": "http://localhost:3001/"

Dil*_*ble 7

默认情况下,Fetch 将访问您正在使用它的位置的相对路径。您可以通过以 / 开头的 url 来指定要绕过相对路径。

fetch('/api/listofrentals/2') 
Run Code Online (Sandbox Code Playgroud)