Data method
This guide shows how to receive data from an API with Params, Query and Body.
Params
Params are the required input type in this data method when you need a route parameter.
Single Params
// Single params
app.get("/api/:id", function (req: Request, res: Response) {
const { id } = req.params; // 13
res.json({ data: id });
});Multi params
// Single params
app.get("/api/:id/:name", function (req: Request, res: Response) {
const { id, name } = req.params; // 13, peter
res.json({ data: id, name: name });
});Query
Query is optional in this data method, which means you can still access the API without any query input.
Single Query
// Single query
app.get("/api", function (req: Request, res: Response) {
const { id } = req.query; // 14
res.json({ data: id });
});Multi Query
// Single query
app.get("/api", function (req: Request, res: Response) {
const { id, name } = req.query; // 14, tom
res.json({ data: id, name: name });
});Difference between params and Query
As mentioned above, letโs compare a params-based API and a Query-based API.
app.get("/api/:id", function (req: Request, res: Response) {
const { id } = req.params; // 13
res.json({ data: id });
});- Normal ways โญ
[GET] http://localhost:8080/api/13
Respond: { data: 13 }
- No params cases โ
[GET] http://localhost:8080/api
Respond: 404 Route not foundapp.get("/api", function (req: Request, res: Response) {
const { id } = req.query;
res.json({ data: id });
});// Normal ways โญ
// [GET] http://localhost:8080/api?id=80
// Respond: { data: 80 }
// No query cases โญ
// [GET] http://localhost:8080/api
// Respond: { data: null }With query, the API is still accessible without an ID. If you require the user to provide input, use params instead of query.
:::tip
You can still add constraints to require query input in API logic or use validation libraries / packages like zod, yup, express-validator, or others.
:::
Body
Body is a method to receive HTML form data like <form> elements or body in fetch.
Json data
By default, we need to add express.json() and express.urlencoded({ extended: true }) to let Express parse body data.
// Add these line to your server
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencodedapp.post('/api', function (req, res) {
console.log(req.body);
res.json({
status: true,
data: req.body.id,
name: req.body.name
});
});const res = await fetch( "http://localhost:8080/api" ,{
method:"POST",
headers:{
// Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
},
body: JSON.stringify({
id: 10,
name: "Peter"
});
});
const result = await res.json();
console.log(result);
/*
status: true,
data: 10,
name: "Peter"
*/multipart/form-data
With formidable
https://www.npmjs.com/package/formidable#readmeย
import path from "path"
import fs from "fs"
import formidable, { Fields, Files } from "formidable";
import IncomingForm from "formidable/Formidable";
import { Request } from "express"
// Create a folder if not exist
const uploadDir = "uploads"
const finalDir = path.join(__dirname, "..", uploadDir)
if (!fs.existsSync(finalDir)) {
fs.mkdirSync(finalDir)
}
export const form = formidable({
multiples: true,
uploadDir: finalDir,
keepExtensions: true,
maxFileSize: 1024 * 1024 * 20, // (20mb)
maxFiles: 1,
filter: part => part.mimetype?.startsWith('image/') || false,
filename: (originalName, originalExt, part, form) => {
const ext = part.mimetype?.split("/").pop();
return `${part.name}-${Date.now()}.${ext}`;
},
});
export function formParse(form: IncomingForm, req: Request) {
return new Promise<{ fields: Fields; files: Files }>((resolve, reject) => {
form.parse(req, (err, fields, files) => {
if (err) {
reject(err);
}
resolve({ fields, files });
});
});
}import { formParse } from "formidable"
// [POST] http://localhost:8080/data
app.post('/data', async (req: express.Request, res: express.Response) => {
try{
const data = await formParse(form, req);
return res.status(200).json({
status: true,
bodyData: data.fields, // data.fields : The original form data (No Files)
filesData: data.files // data.files : The media file data from form (Files)
})
}
catch(err:any){
return res.status(200).json({ status: false })
}
});const formData = new FormData();
formData.append("name", "Peter");
const res = await fetch( "http://localhost:8080/data" ,{
method:"POST",
body: formData
});
const result = await res.json();