I have a React/Node app that posts to MongoDB Atlas using Axios. Locally, the app makes calls successfully, but after deploying it on Heroku, I'm getting the following error message in the console:
POST http://localhost net::ERR_CONNECTION_REFUSED; Uncaught (in promise) o {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK
React Frontend:
const handleClick = (event) => {
event.preventDefault();
const newConnection = {
firstName: input.firstName,
lastName: input.lastName,
email: input.email,
comments: input.comments,
date: new Date()
}
axios.post('http://localhost:3001/create', newConnection)
window.alert("Thank you! We will be in touch soon.")
}
Backend Route:
const express = require("express");
const router = express.Router();
const Connection = require("../models/connectionModel");
router.route("/create").post((req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const comments = req.body.comments;
const date = req.body.date;
const newConnection = new Connection({
firstName,
lastName,
email,
comments,
date
});
newConnection.save();
})
module.exports = router;
Backend Server:
const express = require('express');
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
const port = process.env.PORT || 3001;
app.use(cors());
app.use(express.json());
app.use(express.static(path.resolve(__dirname, "./frontend/build")));
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
mongoose.connect(process.env.MONGODB_URI);
app.use("/", require("./routes/connectionRoute"));
app.listen(port, function() {
console.log('express server is running on port 3001')
})
After combing the web for solutions, I confirmed that the express server is running on port 3001 and that I have CORS enabled. It's possible that there's an issue with the url I'm using in the axios.post request, but I'm unsure how to proceed.
Any help would be much appreciated!