0

I am trying to connect an express backend with an react frontend as follows:

express code:

const app = express();
const port = 4000;
var router = express.Router();

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(port, () => {
  //...
});

router.get('/handle',(request,response) => {
  response.send("...");
});
app.use("/", router);
module.exports = router;

React Code (inside a on-click function):

var myRequest = new XMLHttpRequest(),
  method = 'GET',
  url = 'http://127.0.0.1:4000';

  myRequest.open(method, url, true);
  
  myRequest.onerror = function() { 
    alert(`Network Error`);
  };
  myRequest.send();
  myRequest.onload = function() {
    alert(`success`);
  };

When i type http://127.0.0.1/handle into the browser, i get the correct response - so the express server is working. However, when i try to do the request with the react code, i always get "network error". I really have no idea how to fix this, could anyone give me a hint? (React app is also running on localhost)

azes
  • 13
  • 7
  • Are there any error messages displayed in the browser's developer tools console? – Quentin May 10 '22 at 14:00
  • 10:1 that this turns out to be another duplicate of https://stackoverflow.com/a/35553666/19068 – Quentin May 10 '22 at 14:01
  • Access to XMLHttpRequest at 'http://127.0.0.1:4000/' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – azes May 10 '22 at 14:01
  • … and I should I have put money on that bet. – Quentin May 10 '22 at 14:02
  • Thanks... so if i fix the CORS, it should work? – azes May 10 '22 at 14:02

0 Answers0