1
votes

I created two very basic applications to study on requests. One is a React app and the other is Express. I am trying to make a POST request from the frontend React application using "axios". The React app listens to port 3000 while the backend Express app listens to 4200. Thus my code is:

React app (front end).This is my App component where index.js leads to:

 componentDidMount() {
    
    axios.post("http://127.0.0.1:4200", "hello").then(res =>{
      alert("Sent");
    }).catch(console.error)
  }

  render() {
    return (
      <div>
        <p>Hello World!</p>
      </div>
    )
  }

Express app.js axios part:

axios = require("axios");
axios.get("/" ).then(function(){
  console.log("I listened");}
).catch(err=> {
  console.log(err);
});

However I got this error from the "inspect" option of the frontend app (localhost:3000)

index.js:1 Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:83)

and

VM343:45 POST http://127.0.0.1:4200/ net::ERR_CONNECTION_REFUSED

Any idea why? Thanks

1
Your express app.js isn't express at all. Its axios. - tkausl
@tkausl It's only partial code. The rest is express. Maybe I should edit what I meant. - codertryer
why don't you try express router in express ? expressjs.com/en/starter/basic-routing.html check this link... have a look on how express routing works - vishnusaran

1 Answers

0
votes

As @vishnusaran said, I used express router and it worked.