Q1. What are the most common HTTP methods used in Express?
GET (retrieve data), POST (create new resource), PUT (update entire resource), PATCH (partial update), DELETE (remove resource).
These correspond to CRUD operations: Create (POST), Read (GET), Update (PUT/PATCH), Delete (DELETE).
These correspond to CRUD operations: Create (POST), Read (GET), Update (PUT/PATCH), Delete (DELETE).
Q2. How do you handle a GET request in Express?
Use
Example:
app.get().Example:
app.get('/users', (req, res) => {
const users = [{id:1, name:'John'}];
res.json(users);
});
GET requests typically retrieve data and should not modify server state. They can include query parameters in the URL.Q3. How do you handle a POST request?
Use
You'll need middleware like
Example:
app.post(). POST is used to create new resources.You'll need middleware like
express.json() to parse the request body.Example:
app.post('/users', express.json(), (req, res) => {
const newUser = req.body;
// save to database
res.status(201).json(newUser);
});
Q4. What's the difference between PUT and PATCH?
PUT replaces an entire resource. You send the complete updated object.
PATCH applies partial modifications – you only send the fields that changed.
In Express, both are handled similarly with
PATCH applies partial modifications – you only send the fields that changed.
In Express, both are handled similarly with
app.put() and app.patch(), but the implementation logic differs.Q5. How do you handle a DELETE request?
Use
Example:
app.delete(). Usually you identify the resource by ID, often from URL parameters.Example:
app.delete('/users/:id', (req, res) => {
const id = req.params.id;
// delete user with this id
res.status(204).send();
});
204 means success with no content.