Creating documents means making new files or data entries on the server. This helps store information like user details or messages.
When a user signs up and you want to save their info.
When someone submits a form and you need to keep their answers.
When you want to add a new blog post or article to your website.
When you want to save a new product in an online store.
When you want to log events or actions happening in your app.
Syntax
Express
app.post('/path', (req, res) => {
// get data from req.body
// save data to database or file
res.send('Document created')
})
Use app.post to handle creating new data because POST means sending new info.
Access the data sent by the user with req.body after using middleware like express.json().
Examples
This example creates a new user from the data sent in the request.
Express
app.post('/users', (req, res) => {
const user = req.body
// pretend to save user
res.send(`User ${user.name} created`)
})
Here, a new note is created and the server responds with status 201 meaning 'created'.
Express
app.post('/notes', (req, res) => {
const note = req.body
// save note to database
res.status(201).send('Note created')
})
Sample Program
This program creates a simple Express server that accepts POST requests to /documents. It expects a JSON body with title and content. If both exist, it saves the document in an array and replies with a success message.
Hint: Always enable express.json() before accessing req.body [OK]
Common Mistakes:
Thinking res.send must be res.json
Using app.get for creation routes
Assuming saveUser must be async here
5. You want to create an Express route that accepts JSON data to create a new product and respond with the created product including an ID. Which code snippet correctly implements this?
Step 1: Use correct HTTP method and access JSON body
The route uses app.post and accesses req.body which is correct for creating a product.
Step 2: Add an ID and respond with status 201 and JSON
Assigning product.id = Date.now() simulates creating an ID. Responding with res.status(201).json(product) sends the created product with proper status.