Frontend fetching data from unexpected localhost address despite proxy configuration

25 views Asked by At

I have a React frontend application configured with a proxy in the package.json file pointing to my Flask backend running on http://localhost:2371. However, when making requests to fetch data from the backend using fetch("/members"), the frontend seems to be fetching data from localhost:5173 (the address on which the react site is running) instead of the expected localhost:2371. I've double-checked the proxy configuration (Here is my package.json):

 "name": "react-frontend",
 "private": true,
 "proxy": "http://localhost:2371",
 "version": "0.0.0",
 "type": "module",

and ensured that the backend server is running, but I'm still encountering this issue. What could be causing the frontend to fetch data from the unexpected localhost address instead of the configured proxy? The code works if I fetch from the whole address ("http://localhost:2371/members"), but it would be simpler to just write "/members". Do I need to import the package.json to my App.tsx to make it work or is it alredy somehow connected? Here is my backend script:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/members")
def members():
    return jsonify({"members": ["Mem1", "Mem2", "Mem3"]})

if __name__ == "__main__":
    app.run(debug=True, port=2371)

Any insights or suggestions for troubleshooting would be greatly appreciated. Thank you!

1

There are 1 answers

3
Sanket Sharma On

Try replacing localhost with 127.0.0.1

"proxy": "http://127.0.0.1:2371",

Your package.json should look something like this

    {
  "name": "something",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:2371",
  "dependencies": {
    
  },
  "scripts": {
    
  },
  "eslintConfig": {
    "extends": [
      
    ]
  },
  "browserslist": {
    "production": [
     
    ],
    "development": [

    ]
  }
}

Now if you want to fetch data every time the page is loaded then you should do this.

import { useState, useEffect } from 'react';


function App() {
  const [members, setMembers] = useState([]);

  useEffect(() => {
    fetch('/members').then(response => response.json())
    .then(data => setMembers(data))
  }, []);


  console.log(members)
  return (
    <h1>Members</h1>
  );
}

export default App;

Using your codebase the above code will fetch the data from "http://localhost:2371/members" every time the page reloads.