0
0
Expressframework~5 mins

Creating documents in Express

Choose your learning style9 modes available
Introduction

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.

Express
import express from 'express'

const app = express()
app.use(express.json())

const documents = []

app.post('/documents', (req, res) => {
  const doc = req.body
  if (!doc.title || !doc.content) {
    return res.status(400).send('Missing title or content')
  }
  documents.push(doc)
  res.status(201).send(`Document titled '${doc.title}' created`)
})

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})
OutputSuccess
Important Notes

Always use express.json() middleware to read JSON data sent by clients.

Use status code 201 to clearly say a new resource was created.

Validate the incoming data to avoid saving incomplete documents.

Summary

Use app.post to create new documents or data entries.

Access user data with req.body after enabling JSON parsing.

Send a clear response with status 201 when creation is successful.