Design an Express route to create a user
REST conventions for creation.
POST to a collection URL like /users, read the payload from req.body via express.json(), return 201 with the created resource.
using GET to create or putting data in the URL.
WHAT THIS TESTS This assesses whether you apply REST conventions correctly: the right verb, a resource-oriented URL, and the proper place to read input.
A GOOD ANSWER COVERS Creating a resource maps to the POST method against the collection endpoint, so the URL is /users (a plural noun, with no verb like /createUser in the path). The client sends the user's data in the request body as JSON, and with express.json() registered the parsed fields land on req.body, where you read req.body.name, req.body.email, and so on. You validate the input, persist it, and respond with 201 Created, ideally returning the created resource and a Location header pointing to /users/:id. Using POST signals a non-idempotent creation, distinct from GET which must be safe and side-effect free.
COMMON WRONG ANSWERS Using GET to create data, which violates HTTP safety semantics and can be cached or retried unexpectedly. Putting fields in the URL or query string instead of the body. Returning 200 instead of 201 for a creation. Forgetting express.json() so req.body is undefined. Naming the route with a verb like /addUser.
LIKELY FOLLOW-UPS Why 201 over 200? What goes in the Location header? How do you validate the body? What status for a duplicate email (409)?
ONE CONCRETE EXAMPLE app.post('/users', async (req, res) => { const { name, email } = req.body; const user = await db.users.create({ name, email }); res.status(201).location(/users/${user.id}).json(user); }); A client POSTs { "name": "Ada", "email": "ada@x.com" } to /users, the parser fills req.body, the record is saved, and the API returns 201 with the new user and a Location header, the textbook REST creation flow.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.