Parker
Parker

Reputation: 63

How do you get a react app to communicate properly with a server that is on the same ec2 instance?

I have built a very small SERN app that was making requests to the back end api just fine when I was testing it on my computer but when deployed to ec2 the front and back end were no longer able to communicate with one another. Here is some of my server side code:

// Configure Express app
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: false,
}));
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

// Endpoint to add a new box
app.post('/api/addBox', async (req, res) => {
  console.log(req.body);
  const box = req.body;
  try {
    const result = await boxTable.addBox(box);
    res.send(result);
    console.log(result);
  } catch (error) {
    console.log(error);
    res.status(400).send(error);
  }
});

// Start the server
const PORT = process.env.PORT || 3001;
const server = app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);

And here is an example api call from the front end:

const handleConfirmDelete = async () => {
    setError('');
    try {
      await axios.post(`${config.apiUrl}:${config.apiPort}/api/deleteBox`, { name: boxToDelete.name });
      fetchBoxes(); // Fetch the updated boxes list
      setIsDeleteModalOpen(false);
      setBoxToDelete(null);
    } catch (error) {
      setError(`Error deleting box: ${error.response ? error.response.data : error.message}`);
    }
  };

The config.apiUrl is 'http://localhost' and the port is 3001 in the config file.

I set up the front end package.json to proxy to "http://localhost:3001".

I keep getting a cors error though for all requests from the front end:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://54.86.29.70:3001/api/addBox. (Reason: CORS request did not succeed). Status code: (null).

I am accessing the front end via the public IP on port 3000 successfully, it's just not populating any of the fields. It's my first time deploying an app like this so go easy on me. :)

Upvotes: 0

Views: 46

Answers (1)

Parker
Parker

Reputation: 63

Okay, I was able to solve the issue myself. It looks like I forgot to open the port 3001 in the inbound rules.

Upvotes: 0

Related Questions