setup proxy setting for React client

* eliminate needs to type fetch() base url
main
yikth 5 years ago
parent 4a6b82a5bd
commit 8be001ddfa

@ -16,6 +16,7 @@
"test": "react-scripts test", "test": "react-scripts test",
"eject": "react-scripts eject" "eject": "react-scripts eject"
}, },
"proxy": "http://localhost:7000",
"eslintConfig": { "eslintConfig": {
"extends": "react-app" "extends": "react-app"
}, },

@ -28,6 +28,10 @@
text-align: left; text-align: left;
} }
.App-list {
text-align: left;
}
.App-link { .App-link {
color: #61dafb; color: #61dafb;
} }

@ -9,20 +9,21 @@ class App extends React.Component {
} }
callAPIServer() { callAPIServer() {
let bodyData = { /* let bodyData = {
limit: 12, limit: 12,
}; }; */
console.log(JSON.stringify(bodyData)); // setup automatic proxy in package.json.
fetch("http://localhost:7000/users?limit=8", { // thus eliminating the need to type "http://localhost:7000"
// "proxy" : "http://localhost:7000"
fetch("/users?limit=18", {
method: "GET", method: "GET",
/* body: JSON.stringify(bodyData), */ /* body: JSON.stringify(bodyData), */
headers: { "Content-type": "application/json; charset=UTF-8" }, headers: { "Content-type": "application/json; charset=UTF-8" },
}).then((res) => res.text()) }).then((res) => res.json())
.then((res) => { .then((data) => {
console.log(res); console.log(data);
console.log(JSON.parse(res)); this.setState({ serverResponse: JSON.stringify(data), user: data });
this.setState({ serverResponse: res, user: JSON.parse(res) });
console.log(this.state.user); console.log(this.state.user);
}) })
.catch((err) => { .catch((err) => {
@ -30,7 +31,7 @@ class App extends React.Component {
return err; return err;
}); });
} }
//return <ul>{this.state.tags.map(tag => <li key={tag}>{tag}</li>)}</ul>;
componentDidMount() { componentDidMount() {
// react lifecycle method componentDidMount() // react lifecycle method componentDidMount()
// will execute the callAPIServer() methods afteer the component mounts // will execute the callAPIServer() methods afteer the component mounts
@ -47,15 +48,15 @@ class App extends React.Component {
</h1> </h1>
{/* <h2 className="App-intro">{this.state.serverResponse}</h2> */} {/* <h2 className="App-intro">{this.state.serverResponse}</h2> */}
</header> </header>
<body className="App-body"> <div className="App-list">
<ul> <ul>
{this.state.user.map((item) => ( {this.state.user.map((item) => (
<li> <li key={item.user_id}>
{item.user_id} {item.name} {item.mail} {item.user_id} {item.name} {item.mail}
</li> </li>
))} ))}
</ul> </ul>
</body> </div>
</div> </div>
); );
} }

Loading…
Cancel
Save