I have a simple API with symfony, run on http://127.0.0.1:8000 and a React project who run on http://localhost:3000.
I want to get this :
{"0":{"id":51,"nom":"Ouais","prenom":"ssdds","competences":{}},"1":{"id":52,"nom":"Ouais","prenom":"ssdds","competences":{}},"2":{"id":53,"nom":"Alexis","prenom":"un truc","competences":{}}}
URL = http://127.0.0.1:8000/api/collaborateurs
So, in react i do :
import React, { Component } from "react";
import './App.css';
fetch('/api/collaborateurs')
.then(response => console.log(response))
.then(json => console.log(json))
class App extends Component {
render() {
return (<div className="App">
<h1>Salope</h1>
</div>)
}
}
export default App;
but
console.log(response)
return :
Response {type: "basic", url: "http://localhost:3000/api/collaborateurs", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/api/collaborateurs"
__proto__: Response
why url: "http://localhost:3000/api/collaborateurs" i want url: "**http://127.0.0.1:8000**/api/collaborateurs"
if i change fetch('/api/collaborateurs') to fetch('http://127.0.0.1/api/collaborateurs') the console.log not working
Thank you
Create React App
- Proxying API Requests in Development -- setupProxy.js
IP http://127.0.0.1:8000 = IP http://localhost:8000
People often serve the front-end React app from the same host and port as their backend implementation.
Such setup is not required. However, if you do have a setup like this, it is convenient to write requests like fetch('/api/todos')
without worrying about redirecting them to another host or port during
To tell the development server to proxy any unknown requests to your API server in development, add a proxy
field to your package.json
, for example:
"proxy": "http://localhost:8000",
You can use this feature in conjunction with the proxy
property in package.json
, but it is recommended you consolidate all of your logic into src/setupProxy.js
.
First, install http-proxy-middleware
using npm or Yarn:
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
Next, create src/setupProxy.js
and place the following contents in it:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
How use to FrontEnd React?
fetch('/api/collaborateurs')
.then(response => console.log(response))
.then(json => console.log(json))
https://medium.com/bb-tutorials-and-thoughts/react-how-to-proxy-to-backend-server-5588a9e0347
https://medium.com/@Pavan_/set-up-proxy-to-work-with-multiple-apis-in-create-react-app-be595a713eb2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With