2017-09-27 10 views
0

React.js와 Node.js를 익히고 백엔드에는 Express API를, 프런트 엔드에는 React.js를 사용하여 간단한 애플리케이션을 만듭니다. 내 React.js의 App.js는 이렇게 보입니다.
반응이없는 API를 가져오다가 잘못된 URL을 보내려합니다.

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

난 당신이/대여에 가면 때, 데이터 및 인쇄 물건을 가져올 것을 응용 프로그램을 만드는 중이라서. 현재 작동 중이며 데이터베이스의 모든 데이터가 렌더링 중입니다.
이제/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; 

, 나는 내가 URL http://localhost:3000/api/listofrentals/2에서 가져 오기 위해 노력하고하고 "대여"부분은 URL에 왜 이해가 안 GET http://localhost:3000/rentals/api/listofrentals/2 404 (Not Found) 말하는 오류가 발생합니다. My React 서버가 localhost : 3000에서 실행 중이며 node.js가 localhost : 30001에서 실행 중입니다. 그리고 내 React의 패키지 .json이 있습니다 "proxy": "http://localhost:3001/"

답변

1

기본적으로 가져 오기는 사용중인 상대 경로의 상대 경로에 액세스합니다. /로 URL을 시작하여 상대 경로를 무시하도록 지정할 수 있습니다.

fetch('/api/listofrentals/2') 
+0

. 고맙습니다. 나는'fetch (./../ api/listofrentals/2)와 같은 것을함으로써 그것을 우회하고 있었다. – craftdeer