craftdeer
craftdeer

Reputation: 1025

Fetching API from react sending me wrong URL

Learning React.js and Node.js and making a simple crud app with Express API on the back-end and React.js on the front end. App.js of my React.js looks like this.

    `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;

I am making an app that when if you go to /rentals, it will fetch the data and print stuff. This is currently working and all the data from my database is rendering.
Now I am trying to go to /rentals/1 or /rentals/2 then trying to print only listings of that 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;

When I do this, I get an error saying GET http://localhost:3000/rentals/api/listofrentals/2 404 (Not Found) I am trying to fetch from the URL http://localhost:3000/api/listofrentals/2 and do not understand why the "rentals" part is in the url. My React server is running on localhost:3000 and node.js is running on localhost:30001. And my React's package.json has this "proxy": "http://localhost:3001/"

Upvotes: 2

Views: 4808

Answers (2)

madhu131313
madhu131313

Reputation: 7386

In case if you want to change the base url for testing. You can turn off web security in Google and use. In ubuntu command line it is

google-chrome --disable-web-security --user-data-dir

Upvotes: 0

DillGromble
DillGromble

Reputation: 383

Fetch by default will access a relative path to where you are using it. You can specify you want to bypass the relative path by starting your url with /.

fetch('/api/listofrentals/2') 

Upvotes: 7

Related Questions