I am new to web development and I have a hosting service on which I want to deploy my reactjs/node project. To deploy it previously, I had been simply uploading the build folder created from running npm run build
. I have since added a connection to a mongodb database using the MERN stack.
The project was initially created using create-react-app, then I set up my backend node/mongodb following this tutorial: https://appdividend.com/2018/11/11/react-crud-example-mern-stack-tutorial/. All of my server code is contained within the project folder in an api folder.
I am able to run the project on local host by running npm start
, nodemon server.js
(from the api folder) and connecting to the mongodb in terminal. When I try to run it from the hosting service in the same way I did previously, it says it cannot connect to the database, which I assume is due to the fact that the connection is not open on my machine.
Currently, all the API calls are using axios post to http://localhost:4000/, which I would also assume will not work on the server. I have looked online for information regarding deploying the MERN stack, but all of the ones I have found discuss it in terms of hosting on AWS EC2, which is not what I will be doing.
How would I be able to deploy to my hosting service? Are there any references or places I should look for this information?
Edit: I have connected to the database using MongoAtlas, so am using a SRV address. I think the issue is the axios posts using the localhost address, as the app on the server only works if I have nodemon running on my local machine. What address should I use instead of this?
Currently, all the API calls are using axios post to http://localhost:4000/, which I would also assume will not work on the server.
You're correct, that will not work. That's because if users get your React app, all API calls will be redirect to their localhost
. Which doesn't hold your API
When I try to run it from the hosting service in the same way I did previously, it says it cannot connect to the database, which I assume is due to the fact that the connection is not open on my machine.
That is probably because the MongoDB URL is probably still set to something like 'mongodb://localhost:27017/myapp
. There are 2 main options here.
localhost
URLI have looked online for information regarding deploying the MERN stack, but all of the ones I have found discuss it in terms of hosting on AWS EC2, which is not what I will be doing.
Since you're using MongoDB Atlas make sure you white-listed the IP adress of your server