request
The request object represents the incoming HTTP request to your mim. It is passed as the second parameter to your mim handler.
mimikModule.exports = (context, request, response) => {
// request contains incoming HTTP data
};
Properties
| Property | Type | Description |
|---|---|---|
url | string | Full URL including query string |
method | string | HTTP method (GET, POST, PUT, DELETE, etc.) |
headers | object | HTTP headers (lowercase keys) |
body | string | Request body (for POST/PUT requests) |
authorization | string | Authorization header value |
Methods
| Method | Description |
|---|---|
handleFormRequest(options) | Handle multipart/form-data for file uploads |
url
The full URL of the request including the query string.
app.get('/users', (request, response) => {
console.log(request.url);
// "/users?page=1&limit=10"
});
Parsing Query Parameters
app.get('/search', (request, response) => {
// Simple query parsing
var url = request.url;
var queryStart = url.indexOf('?');
if (queryStart !== -1) {
var queryString = url.substring(queryStart + 1);
var params = {};
queryString.split('&').forEach(function(pair) {
var parts = pair.split('=');
params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1] || '');
});
response.end(JSON.stringify(params));
} else {
response.end('{}');
}
});
method
The HTTP method of the request.
app.all('/resource', (request, response) => {
if (request.method === 'GET') {
// Handle GET
response.end('GET request');
} else if (request.method === 'POST') {
// Handle POST
response.end('POST request');
} else if (request.method === 'PUT') {
// Handle PUT
response.end('PUT request');
} else if (request.method === 'DELETE') {
// Handle DELETE
response.end('DELETE request');
} else {
response.statusCode = 405;
response.end('Method not allowed');
}
});
headers
HTTP headers as a key-value object. Header names are lowercase.
app.post('/data', (request, response) => {
var contentType = request.headers['content-type'];
var userAgent = request.headers['user-agent'];
var customHeader = request.headers['x-custom-header'];
response.end(JSON.stringify({
contentType: contentType,
userAgent: userAgent,
customHeader: customHeader
}));
});
Common Headers
app.get('/headers', (request, response) => {
response.end(JSON.stringify({
contentType: request.headers['content-type'],
accept: request.headers['accept'],
userAgent: request.headers['user-agent'],
host: request.headers['host'],
origin: request.headers['origin'],
referer: request.headers['referer']
}));
});
body
The request body as a string. Available for POST, PUT, and PATCH requests when the Content-Type is application/json.
app.post('/users', (request, response) => {
var user = JSON.parse(request.body);
console.log(user.name);
console.log(user.email);
// Save user...
response.statusCode = 201;
response.end(JSON.stringify({ id: 123, created: true }));
});
Handling JSON Body
app.post('/data', (request, response) => {
try {
var data = JSON.parse(request.body);
// Process data...
response.end(JSON.stringify({ success: true }));
} catch (e) {
response.statusCode = 400;
response.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
authorization
The Authorization header value, typically containing a Bearer token.
app.get('/protected', (request, response) => {
if (!request.authorization) {
response.statusCode = 401;
response.end('Unauthorized');
return;
}
// Extract token from "Bearer <token>"
var parts = request.authorization.split(' ');
if (parts[0] !== 'Bearer' || !parts[1]) {
response.statusCode = 401;
response.end('Invalid authorization format');
return;
}
var token = parts[1];
// Validate token...
response.end('Access granted');
});
Passing Token to Other Services
app.get('/proxy', (request, response) => {
context.http.request({
url: 'http://127.0.0.1:' + context.info.httpPort + '/other-mim/v1/data',
authorization: request.authorization, // Forward the token
success: function(result) {
response.end(result.data);
},
error: function(err) {
response.statusCode = err.status || 500;
response.end(err.message);
}
});
});
handleFormRequest()
Handles multipart/form-data POST requests for file uploads and form fields.
request.handleFormRequest(options)
Options
| Option | Type | Description |
|---|---|---|
found | function | Called when a field/file is found; returns action |
get | function | Called with field value when action is 'get' |
store | function | Called after file is stored when action is 'store' |
found Callback
found: (name, filename) => {
// name: field name
// filename: file name (empty string for text fields)
return {
action: 'get' | 'store' | 'skip' | 'abort',
path: '/path/to/save' // Required for 'store' action
};
}
Actions
| Action | Description |
|---|---|
'get' | Process as text field; triggers get() callback |
'store' | Save as file; triggers store() callback |
'skip' | Ignore this field |
'abort' | Stop processing the form |
Example: File Upload
app.post('/upload', (request, response) => {
var uploadedFiles = [];
var formFields = {};
request.handleFormRequest({
found: function(name, filename) {
if (filename) {
// It's a file
if (filename.endsWith('.jpg') || filename.endsWith('.png')) {
return { action: 'store', path: 'uploads/' + filename };
}
return { action: 'skip' }; // Skip non-image files
}
// It's a text field
return { action: 'get' };
},
get: function(name, value) {
formFields[name] = value;
},
store: function(filepath, bytesStored) {
uploadedFiles.push({
path: filepath,
size: bytesStored
});
}
});
response.end(JSON.stringify({
files: uploadedFiles,
fields: formFields
}));
});
Example: Profile Update with Avatar
app.post('/profile', (request, response) => {
var profile = {};
var avatarPath = null;
request.handleFormRequest({
found: function(name, filename) {
if (name === 'avatar' && filename) {
var ext = filename.split('.').pop();
avatarPath = 'avatars/user-' + Date.now() + '.' + ext;
return { action: 'store', path: avatarPath };
}
return { action: 'get' };
},
get: function(name, value) {
profile[name] = value;
},
store: function(filepath, bytesStored) {
profile.avatar = filepath;
profile.avatarSize = bytesStored;
}
});
// Save profile...
context.storage.setItem('profile:' + profile.id, JSON.stringify(profile));
response.end(JSON.stringify({ success: true, profile: profile }));
});
Router Parameters
When using a router library, route parameters are typically available on request.params:
import Router from 'router';
var app = Router({ mergeParams: true });
app.get('/users/:id', (request, response) => {
var userId = request.params.id;
// ...
});
app.get('/posts/:postId/comments/:commentId', (request, response) => {
var postId = request.params.postId;
var commentId = request.params.commentId;
// ...
});
Related
- response: Response methods
- context.http: HTTP client API
- context.storage: Persistent storage API
- context.info: Node metadata and environment