In this article, I’ll walk you through my journey of building and deploying a Node.js CRUD API, the errors I encountered along the way, and how I resolved them. This project was hosted on Render, a cloud platform that simplifies deployment and scaling of web applications. I’ll cover the key steps, challenges, and solutions to help you avoid similar pitfalls.
Project Overview
The goal of the project was to build a simple CRUD (Create, Read, Update, Delete) API using Node.js and Express. The API allows users to perform basic operations on a resource, such as adding, retrieving, updating, and deleting data. The application was deployed to Render for public access.
Key Features
POST /api/add: Add new data.
GET /api/data: Retrieve all data.
PUT /api/data/🆔 Update data by ID.
DELETE /api/data/🆔 Delete data by ID.
Step 1: Setting Up the Project
I started by initializing a Node.js project and installing the necessary dependencies:
bash
Copy
npm init -y
npm install express cors
Basic Server Setup
Here’s the initial structure of the application:
javascript
Copy
const express = require("express");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
let data = [];
// POST /api/add
app.post("/api/add", (req, res) => {
const newData = req.body;
data.push(newData);
res.json({ message: "Data added", data: newData });
});
// GET /api/data
app.get("/api/data", (req, res) => {
res.json(data);
});
app.listen(port, () => {
console.log(Server running on port ${port}
);
});
Step 2: Deploying to Render
After testing the application locally, I decided to deploy it to Render. Here’s how I did it:
Pushed the code to GitHub:
bash
Copy
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/username/repo-name.git
git push -u origin main
Created a Web Service on Render:
Connected my GitHub repository to Render.
Set the Build Command to npm install.
Set the Start Command to node index.js.
Added Environment Variables:
Since the app uses process.env.PORT, I didn’t need to add any additional environment variables.
Deployed the Application:
Render automatically built and deployed the app.
The app was accessible at https://tsicrudassignment.onrender.com.
Step 3: Errors and Fixes
During the development and deployment process, I encountered several errors. Here’s how I resolved them:
Error 1: Cannot GET /api/add
Problem:
When I tried to access https://tsicrudassignment.onrender.com/api/add in my browser, I got the error:
Copy
Cannot GET /api/add
Cause:
The browser sends a GET request by default, but the /api/add endpoint only accepts POST requests.
Solution:
I tested the endpoint using Postman and cURL to send a POST request:
bash
Copy
curl -X POST https://tsicrudassignment.onrender.com/api/add \
-H "Content-Type: application/json" \
-d '{"name": "John", "age": 30}'
This worked, and I received the expected response:
json
Copy
{
"message": "Data added",
"data": {
"name": "John",
"age": 30
}
}
Error 2: Cannot PUT /api/data/2
Problem:
When I tried to update data using a PUT request, I got the error:
Copy
Cannot PUT /api/data/2
Cause:
The PUT route was not defined in my Express app.
Solution:
I added the PUT route to handle updates:
javascript
Copy
app.put("/api/data/:id", (req, res) => {
const id = parseInt(req.params.id);
const updatedData = req.body;
data[id] = updatedData;
res.json({ message: "Data updated", data: updatedData });
});
After redeploying, the PUT request worked as expected.
Error 3: Cannot find module 'update/lib/utils'
Problem:
During deployment, Render logs showed the error:
Copy
Error: Cannot find module 'update/lib/utils'
Cause:
The update module was not installed or was incorrectly referenced.
Solution:
I checked my package.json and installed the missing dependency:
bash
Copy
npm install update
I also verified that the module was correctly referenced in my code.
Error 4: Deployment Failed with Exited with status 1
Problem:
The deployment failed with the error:
Copy
==> Exited with status 1
Cause:
This error is generic and can occur for various reasons, such as missing dependencies or incorrect start commands.
Solution:
I checked the Render logs and found that the start script in package.json was incorrect. I updated it to:
json
Copy
"scripts": {
"start": "node index.js"
}
After redeploying, the application started successfully.
Step 4: Final Application
After fixing all the errors, the final application worked as expected. Here’s the complete code:
index.js:
javascript
Copy
const express = require("express");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
let data = [];
// POST /api/add
app.post("/api/add", (req, res) => {
const newData = req.body;
data.push(newData);
res.json({ message: "Data added", data: newData });
});
// GET /api/data
app.get("/api/data", (req, res) => {
res.json(data);
});
// PUT /api/data/:id
app.put("/api/data/:id", (req, res) => {
const id = parseInt(req.params.id);
const updatedData = req.body;
data[id] = updatedData;
res.json({ message: "Data updated", data: updatedData });
});
// DELETE /api/data/:id
app.delete("/api/data/:id", (req, res) => {
const id = parseInt(req.params.id);
data.splice(id, 1);
res.json({ message: "Data deleted" });
});
app.listen(port, () => {
console.log(Server running on port ${port}
);
});
Conclusion
Building and deploying a Node.js CRUD API was a great learning experience. I encountered several challenges, but by carefully analyzing the errors and testing my code, I was able to resolve them. Render made deployment straightforward, and I now have a fully functional API hosted in the cloud.
If you’re working on a similar project, I hope this article helps you avoid common pitfalls and deploy your application successfully. Happy coding! 🚀
Top comments (0)