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)