Consider an Express app with two routes: one handling PUT /user/:id and another handling PATCH /user/:id. Both update user data in a database.
What is the main difference in how these routes should behave when updating a user?
Think about full replacement versus partial update.
PUT is meant to replace the entire resource, so the server expects a full user object. PATCH is for partial updates, so only the fields to change are sent.
Which of the following code snippets correctly defines a PATCH route for updating a user's email in Express?
const express = require('express');
const app = express();
app.use(express.json());Check method name casing and syntax.
Express methods are lowercase. Both arrow functions and named functions work, but the question asks for correct syntax, so uppercase method is invalid.
Given this Express PUT route code, why does the user data not update as expected?
app.put('/user/:id', (req, res) => {
const id = req.params.id;
const newData = req.body;
const user = users.find(u => u.id === id);
Object.assign(user, newData);
res.send(user);
});Check data types when searching in arrays.
The id from URL params is a string, but user IDs in the array are numbers, so find returns undefined and Object.assign fails silently.
Assume the user object before the PATCH request is:
{"id":1,"name":"Alice","email":"alice@example.com","age":30}The PATCH request body is:
{"email":"alice.new@example.com","age":31}What will the user object look like after the PATCH route updates it with Object.assign(user, req.body)?
Think about how Object.assign merges objects.
Object.assign updates existing properties and adds new ones but keeps properties not overwritten. So only email and age change.
In REST API design, why is it generally better to use PATCH instead of PUT when updating only some fields of a resource?
Consider network efficiency and data safety.
PATCH updates only specified fields, so clients send less data and avoid accidentally overwriting fields they don't intend to change. PUT replaces the entire resource, which can cause data loss if fields are missing.