### Create a basic nanoexpress.js server Source: https://nanoexpress.js.org/index Demonstrates how to create a simple nanoexpress.js server that listens for GET requests on the root path and responds with a JSON object. This example assumes nanoexpress has already been installed. ```javascript import nanoexpress from 'nanoexpress'; const app = nanoexpress(); app.get('/', (req, res) => { return res.send({ status: 'ok' }); }); app.listen(3000); ``` -------------------------------- ### Install nanoexpress.js using npm or yarn Source: https://nanoexpress.js.org/index Installs the nanoexpress.js library to your project. This is the first step before creating a server. Supports both npm and yarn package managers. ```bash $ npm i nanoexpress # or $ yarn add nanoexpress ``` -------------------------------- ### Basic WebSocket Configuration in nanoexpress Source: https://nanoexpress.js.org/websocket This example shows a basic setup for a WebSocket server using nanoexpress, configuring essential options like compression, payload length, and idle timeout. It also defines handlers for WebSocket connection, message, drain, and close events. ```javascript app.ws('/', { /* Options */ compression: uWS.SHARED_COMPRESSOR, maxPayloadLength: 16 * 1024 * 1024, idleTimeout: 10, /* Handlers */ open: (ws) => { console.log('A WebSocket connected!'); }, message: (ws, message, isBinary) => { /* Ok is false if backpressure was built up, wait for drain */ let ok = ws.send(message, isBinary); }, drain: (ws) => { console.log('WebSocket backpressure: ' + ws.getBufferedAmount()); }, close: (ws, code, message) => { console.log('WebSocket closed'); } }); ``` -------------------------------- ### sendFile Example Source: https://nanoexpress.js.org/routes/response Demonstrates how to send a static file as the response, with a note on file path considerations. ```APIDOC ## GET /video.mp4 ### Description Serves the specified video file (`video.mp4`) as the HTTP response. The file should be located in the same directory as the script or an absolute path can be used. ### Method GET ### Endpoint /video.mp4 ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - The content of the `video.mp4` file. #### Response Example (Binary content of the video file) ``` -------------------------------- ### Redirect + Params Example Source: https://nanoexpress.js.org/routes/response Illustrates how to extract parameters from the URL and perform a redirect after fetching user data. ```APIDOC ## GET /user/:id/login ### Description Retrieves user information based on the provided ID parameter and then redirects the user to their profile page. ### Method GET ### Endpoint /user/:id/login ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier for the user. #### Query Parameters None #### Request Body None ### Response #### Success Response (302) Redirects to `/user/:id/`. #### Response Example (No JSON body for redirect responses, only headers) ``` HTTP/1.1 302 Found Location: /user/123/ ``` ``` -------------------------------- ### Cookie + JSON Example Source: https://nanoexpress.js.org/routes/response Demonstrates how to check for a cookie and send a JSON response based on its presence. ```APIDOC ## GET /is_logged ### Description Checks if the `userId` cookie is present and returns a JSON response indicating success or error. ### Method GET ### Endpoint /is_logged ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **status** (string) - Either 'success' if the cookie exists, or 'error' if it does not. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Redirect User After Database Lookup (JavaScript) Source: https://nanoexpress.js.org/routes/response Handles a GET request to '/user/:id/login'. It extracts the user ID from the URL parameters, retrieves user data from a database, and then redirects the user to their profile page. This example demonstrates the use of 'req.params' and the 'redirect' response method. ```javascript app.get('/user/:id/login', async (req, res) => { const { id } = req.params; const result = await db.getUser(id); return res.redirect(`/user/${id}/`); }); ``` -------------------------------- ### GET / (with Response Serialization) Source: https://nanoexpress.js.org/schemas Example of a GET request with schema-based serialization for the response body. ```APIDOC ## GET / ### Description Handles GET requests to the root endpoint with schema-based serialization for the response body. ### Method GET ### Endpoint / ### Parameters No specific parameters are defined for validation in this example. ### Request Example (No request body or specific parameters shown in this example) ### Response #### Success Response (200) - **hello** (string) - A greeting message. #### Response Example ```json { "hello": "world" } ``` ``` -------------------------------- ### GET / (with Validation) Source: https://nanoexpress.js.org/schemas Example of a GET request with schema validation for headers, disabling validation for query, params, and cookies. ```APIDOC ## GET / ### Description Handles GET requests to the root endpoint with schema validation for request headers. ### Method GET ### Endpoint / ### Parameters #### Query Parameters `query` is set to `false`, disabling query parameter validation. #### Path Parameters `params` is set to `false`, disabling path parameter validation. #### Request Body Not applicable for this GET request example. #### Headers - **authorization** (string) - Required - Specifies the authorization token for the request. ### Request Example ```json { "headers": { "authorization": "Bearer your_token_here" } } ``` ### Response #### Success Response (200) - **hello** (string) - A greeting message. #### Response Example ```json { "hello": "world" } ``` ``` -------------------------------- ### Fix 'git' Missing Error in Dockerfiles (Shell) Source: https://nanoexpress.js.org/docker-linux This snippet addresses the 'git' missing error in Dockerfiles when using minimal Node.js images like 'alpine' or 'slim'. It installs 'git' using the 'apk add' command, which is a common package manager for Alpine Linux. ```shell # FROM ... RUN apk add --no-cache git # your scripts ``` -------------------------------- ### GET / (with HTTP Code-based Serialization) Source: https://nanoexpress.js.org/schemas Example of a GET request with HTTP code-based schema serialization for different response status codes. ```APIDOC ## GET / ### Description Handles GET requests to the root endpoint, defining different response schemas based on HTTP status codes. ### Method GET ### Endpoint / ### Parameters No specific parameters are defined for validation in this example. ### Request Example (No request body or specific parameters shown in this example) ### Response #### Success Response (200) - **hello** (string) - A greeting message. #### Not Found Response (404) - **status** (string) - Indicates the status of the request, e.g., 'Not Found'. #### Response Example (200 OK) ```json { "hello": "world" } ``` #### Response Example (404 Not Found) ```json { "status": "Not Found" } ``` ``` -------------------------------- ### Send a Static File (JavaScript) Source: https://nanoexpress.js.org/routes/response Handles a GET request to '/video.mp4' by sending the 'video.mp4' file. The file should be located in the same directory as the server script or an absolute path can be provided. This utilizes the 'sendFile' response method. ```javascript app.get('/video.mp4', async (req, res) => { return res.sendFile('video.mp4'); }); ``` -------------------------------- ### Nanoexpress.js Precompilation for Static Responses Source: https://nanoexpress.js.org/optimizations Explains and demonstrates the use of the `precompile` option in Nanoexpress.js to cache entire responses. This is suitable for static content but has limitations regarding dynamic values, complex methods, and certain HttpRequest properties. Any `await` calls during compilation will execute only once. ```javascript import { setTimeout } from 'node:timers/promises'; app.get({ precompile: true }, async (req, res) => { await setTimeout(5000); return res.end('string result here'); }); ``` ```javascript app.get({ precompile: true }, (req, res) => { return res.end('success') }); ``` -------------------------------- ### HTTP Request Handling Methods Source: https://nanoexpress.js.org/server Illustrates the instance methods available on a Nanoexpress JS application instance for handling different HTTP request methods. These methods are used to define routes for GET, POST, PUT, PATCH, DELETE, HEAD, and TRACE requests. ```javascript app.get(req, res) app.post(req, res) app.put(req, res) app.patch(req, res) app.del(req, res) app.head(req, res) app.trace(req, res) ``` -------------------------------- ### Handle POST Request with JSON Body and Response Source: https://nanoexpress.js.org/routes/route Example of a POST route handler that receives a JSON body and sends a JSON response. It demonstrates accessing the request body and using `res.send()` to return JSON. ```javascript app.post('/', (req, res) => { const { body } = req; return res.send({ status: 'ok' }); }); ``` -------------------------------- ### Handle Async Route Request with JSON Response Source: https://nanoexpress.js.org/routes/route Example of an asynchronous route handler that returns a JSON object. This is useful for API endpoints that need to send structured data back to the client. ```javascript app.get('/', async () => ({ status: 'success' })); ``` -------------------------------- ### Optimize Request Header Access in Nanoexpress.js Source: https://nanoexpress.js.org/optimizations Demonstrates how the Nanoexpress.js compiler optimizes direct access to request headers within route handlers. This optimization applies to common destructuring patterns and direct property access. Note that optimizations are limited to `req.headers` and `req.params`. ```javascript app.get((req, res) => { const { origin } = req.headers; // This line will be optimized by compiler }); ``` -------------------------------- ### Accessing Request Body in JavaScript Source: https://nanoexpress.js.org/routes/request Provides an example of how to access the request body, for instance, 'username' and 'password' from a POST request in Nanoexpress.js. The request body is often used for submitting data to the server. ```javascript app.post('/user', async (req) => { const { username, password } = req.body; // You can use db.createUser(req.body), but this may cause side-effects const result = await db.createUser({ username, password }); // do something... }); ``` -------------------------------- ### Returning HttpResponse in NanoExpress.js Routes/Middlewares Source: https://nanoexpress.js.org/known-bugs This example demonstrates the correct way to return an HttpResponse from a NanoExpress.js route or middleware. Failing to return the HttpResponse object can lead to errors like 'Invalid access of discarded ...'. Always ensure that `res.send(...)` or similar methods are returned. ```javascript app.get('/', (req, res) => { // Incorrect: res.send('Hello') return res.send('Hello') }); ``` -------------------------------- ### Define Lazy End Method with Middleware (JavaScript) Source: https://nanoexpress.js.org/middlewares This example demonstrates defining a custom method 'lazyEnd' on the response object using a middleware. The 'lazyEnd' method allows for ending the response after a short delay using setTimeout. This is useful for scenarios requiring asynchronous response handling. ```javascript function lazyEnd(end) { setTimeout(() => this.end(end), 0); } app.use((req, res, next) => { res.lazyEnd = lazyEnd; next(); }); ``` -------------------------------- ### Fix CentOS 7 glibc 2.18 Not Found Error in Docker (Shell) Source: https://nanoexpress.js.org/docker-linux This snippet offers two methods to resolve the 'glibc 2.18 not found' error on CentOS 7 when using Docker. It involves installing compatibility packages like 'gcompat' or 'libc6-compat' and adjusting library paths. ```shell # FROM ... RUN apk add --no-cache gcompat # your scripts ``` ```shell # FROM ... RUN apk add --no-cache libc6-compat RUN mv /lib64/ld-linux-x86-64.so.2 /lib # your scripts ``` -------------------------------- ### Set Request Property with Middleware (JavaScript) Source: https://nanoexpress.js.org/middlewares This middleware adds a custom property 'appId' to the request object. It's a basic example of how to modify the request object before it reaches the route handler. No external dependencies are required for this specific middleware. ```javascript app.use((req, res, next) => { req.appId = 'MY_APP_ID'; next(); }); ``` -------------------------------- ### Send JSON Response with Cookie Check (JavaScript) Source: https://nanoexpress.js.org/routes/response Handles a GET request to '/is_logged'. It checks for the presence of a 'userId' cookie and sends a JSON response indicating 'success' or 'error' based on the cookie's existence. This method utilizes the 'hasCookie' and 'send' response methods. ```javascript app.get('/is_logged', async (req, res) => { const status = res.hasCookie('userId') ? 'success' : 'error'; return res.send({ status }); }); ``` -------------------------------- ### Server Configuration Options Source: https://nanoexpress.js.org/server Defines the configuration options available when initializing the Nano Express server, including Swagger integration, AJV configuration, HTTPS settings, and custom console. ```APIDOC ## Server Configuration Options ### Description Provides a structure for configuring the Nano Express server instance. This includes options for Swagger integration, customizing the JSON schema validator (AJV), setting up HTTPS with key, certificate, and passphrase, and defining a custom console for logging. ### Parameters #### Request Body - **swagger** (SwaggerObject) - Optional - Configuration for Swagger integration. - **configureAjv** (function) - Optional - A function to configure the AJV validator. - **https** (object) - Optional - HTTPS configuration object. - **key_file_name** (string) - Required if https is enabled - Path to the SSL private key file. - **cert_file_name** (string) - Required if https is enabled - Path to the SSL certificate file. - **passphrase** (string) - Optional - Passphrase for the SSL private key. - **console** (CustomConsole) - Optional - Custom console object with `log` and `error` functions. ``` -------------------------------- ### HTTP Routing Methods Source: https://nanoexpress.js.org/server Details the standard HTTP method handlers available on the application instance for defining routes. ```APIDOC ## HTTP Routing Methods ### Description These methods are used to define routes for handling different HTTP request methods on the Nano Express application instance. ### Method GET, POST, PUT, PATCH, DELETE, HEAD, TRACE ### Endpoint `/` (Root path, can be any valid path) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (handled by the framework for routing) ### Request Example ```javascript app.get('/', (req, res) => { res.send('Hello World!'); }); ``` ### Response #### Success Response (200) Depends on the route handler implementation. #### Response Example ```json { "message": "Hello World!" } ``` ``` -------------------------------- ### Response Methods Source: https://nanoexpress.js.org/routes/response Provides an overview of the implemented response methods available in NanoExpress.js, based on uWebSockets.js. ```APIDOC ## Response Methods Overview This section details the various methods available on the HTTP response object in NanoExpress.js, which are largely based on the uWebSockets.js library. ### Methods Implemented: * **send**: Sends a response to the client. * **pipe**: Pipes a stream to the response. * **json**: Sends a JSON response (compatible with `send`). * **sendFile**: Sends a file as the response. * **redirect**: Sends a redirect response. * **status**: Sets the HTTP status code. * **writeHead**: Writes the status code and headers. * **cookie**: Sets a cookie. * **setCookie**: Sets a cookie. * **hasCookie**: Checks if a cookie exists. * **removeCookie**: Removes a cookie. * **setHeader**: Sets a response header. * **getHeader**: Gets a response header. * **hasHeader**: Checks if a header exists. * **removeHeader**: Removes a response header. * **setHeaders**: Sets multiple response headers. * **writeHeaderValues**: Writes multiple header values. * **writeHeaders**: Writes multiple headers. * **type**: Sets the Content-Type header. * **header**: Sets a response header. ``` -------------------------------- ### Special Route Handlers Source: https://nanoexpress.js.org/server Describes special route handlers for WebSockets, handling any HTTP method, and OPTIONS requests. ```APIDOC ## Special Route Handlers ### Description Provides handlers for specific non-standard HTTP interactions like WebSockets, a catch-all for any HTTP method, and handling OPTIONS requests for CORS preflight. ### Method WS, ANY, OPTIONS ### Endpoint `/` (Root path, can be any valid path) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (handled by the framework for routing) ### Request Example ```javascript // WebSocket route app.ws('/', (req, ws) => { ws.send('Hello WebSocket!'); }); // Any method route app.any('/', (req, res) => { res.send(`Received a ${req.method} request.`); }); // Options route app.options('/', (req, res) => { res.header('Access-Control-Allow-Origin', '*'); res.send(); }); ``` ### Response #### Success Response (200) Depends on the route handler implementation. #### Response Example ```json { "message": "Received a POST request." } ``` ``` -------------------------------- ### Define Route-middleware using ESM and CJS Source: https://nanoexpress.js.org/routes/route Demonstrates how to define and use a Route-middleware in Nanoexpress JS. It shows both the ESM and CJS import methods. Ensure the router instance is initialized with `app.use()` before registering routes. ```esm import Route from 'nanoexpress/src/Route'; const route = new Route(); app.use(route); route.get('/', async () => 'hello world'); ``` ```cjs const Route = require('nanoexpress/cjs/Route'); const route = new Route(); app.use(route); route.get('/', async () => 'hello world'); ``` -------------------------------- ### Server Configuration Options (TypeScript) Source: https://nanoexpress.js.org/server Defines the configuration object for the Nanoexpress JS server. This includes settings for Swagger integration, Ajv validation configuration, HTTPS certificates and passphrase, and custom console logging. ```typescript { swagger: SwaggerObject, configureAjv(ajv: Ajv): AjvConfigured, https: { key_file_name: string, cert_file_name: string, passphrase: string }, console: CustomConsole { log: function, error: function } } ``` -------------------------------- ### Fix Alpine Incompatible Error in Dockerfiles (Shell) Source: https://nanoexpress.js.org/docker-linux This snippet provides a solution for 'Alpine' incompatibility errors, often related to shared libraries. It creates a symbolic link to ensure the correct dynamic linker is available, which is crucial for many Linux executables when running in an Alpine environment. ```shell # your scripts RUN ln -s /lib/libc.musl-x86_64.so.1 /lib/ld-linux-x86-64.so.2 # your commands # CMD ["node", "server.js"] ``` -------------------------------- ### Special Route Handling Methods Source: https://nanoexpress.js.org/server Details the special route handling methods provided by Nanoexpress JS. This includes methods for handling WebSocket connections (`ws`), accommodating any HTTP method (`any`), and managing OPTIONS requests. ```javascript app.ws(req, ws) app.any(req, res) app.options(req, res) ``` -------------------------------- ### Expose WebSocket Endpoint with nanoexpress Source: https://nanoexpress.js.org/websocket This snippet demonstrates how to expose a WebSocket endpoint at a specified route using nanoexpress's `exposeWebSocket` function. It outlines event handlers for connection, message reception, and connection closure. ```javascript import { exposeWebSocket } from 'nanoexpress/exposes/index.js'; app.ws('/ws', (req, res) => exposeWebSocket({ console.log('Connecting...'); res.on('connection', (ws) => { console.log('Connected'); ws.on('message', (msg) => { console.log('Message received', msg); ws.send(msg); }); ws.on('close', (code, message) => { console.log('Connection closed', { code, message }); }); }); res.on('upgrade', () => { console.log('Connection upgrade'); }); })); ``` -------------------------------- ### Fetch User Data in Async Route Source: https://nanoexpress.js.org/routes/route An asynchronous route handler that fetches user data from a database using `db.getUser(req.params.id)`. It returns the fetched result, assuming `db` is an available database instance. ```javascript app.get('/', async (req, res) => { const result = await db.getUser(req.params.id); return result; }); ``` -------------------------------- ### Basic Async Route with End Response Source: https://nanoexpress.js.org/routes/route A basic asynchronous route handler that sends a simple text response using `res.end()`. This is suitable for straightforward responses where no complex data formatting is needed. ```javascript app.get('/', async (req, res) => { return res.end('hello world'); }); ``` -------------------------------- ### Not Found Handler API Source: https://nanoexpress.js.org/routes/errors-handling Configure a handler to be executed when no route matches the incoming request URL. This is useful for providing custom 404 responses. ```APIDOC ## GET /anyUrl ### Description Sets a handler for requests that do not match any defined routes. This is typically used to return a 404 Not Found response. ### Method GET ### Endpoint /anyUrl ### Parameters #### Path Parameters - **Url** (string) - Required - The requested URL path. ### Response #### Success Response (200) - **code** (integer) - The status code, typically 404. - **message** (string) - A message indicating the URL was not found. #### Response Example ```json { "code": 404, "message": "You entered wrong url" } ``` ``` -------------------------------- ### Request Parameters Source: https://nanoexpress.js.org/routes/request Utilize path parameters to capture dynamic values within the URL, such as user IDs or resource identifiers. ```APIDOC ## GET /user/:id/login ### Description Authenticates a user based on their ID provided in the URL path. ### Method GET ### Endpoint `/user/:id/login` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier for the user. #### Query Parameters None #### Request Body None ### Request Example ```javascript app.get('/user/:id/login', async (req) => { const { id } = req.params; const result = await db.getUser(id); // do something... }); ``` ### Response #### Success Response (200) - **user** (object) - The retrieved user object. #### Response Example ```json { "user": { "id": "123", "username": "john_doe" } } ``` ``` -------------------------------- ### Accessing Request Parameters in JavaScript Source: https://nanoexpress.js.org/routes/request Shows how to retrieve URL parameters, such as an 'id' from a route like '/user/:id/login', in Nanoexpress.js. These parameters are often used to identify specific resources. ```javascript app.get('/user/:id/login', async (req) => { const { id } = req.params; const result = await db.getUser(id); // do something... }); ``` -------------------------------- ### Accessing Request Query String in JavaScript Source: https://nanoexpress.js.org/routes/request Illustrates how to extract query parameters, like a 'token' from a URL such as '/user?token=123', in Nanoexpress.js. Query parameters are typically used for filtering or additional data. ```javascript // /user?token=123 app.get('/user', async (req) => { const { token } = req.query; const result = await jwt.verifyToken(token); // do something... }); ``` -------------------------------- ### HTTP Code-Based Response Serialization in JavaScript Source: https://nanoexpress.js.org/schemas Defines different response schemas based on HTTP status codes (e.g., 200 for success, 404 for not found). This allows for varied response structures depending on the outcome. Ensure required properties are included to prevent server issues. ```javascript app.get( '/', { schema: { response: { 200: { type: 'object', properties: { hello: { type: 'string' } } }, 404: { type: 'object', properties: { status: { type: 'string' } } } } } }, async () => ({ hello: 'world' }) ); app.listen(4000); ``` -------------------------------- ### Response Serialization Schema in JavaScript Source: https://nanoexpress.js.org/schemas Specifies the schema for the response body, ensuring it conforms to the defined structure. Uses fast-json-stringify for optimization. Incorrect schema definitions may lead to data loss without errors. ```javascript app.get( '/', { schema: { response: { type: 'object', properties: { hello: { type: 'string' } } } } }, async () => ({ hello: 'world' }) ); app.listen(4000); ``` -------------------------------- ### Accessing Request Cookies in JavaScript Source: https://nanoexpress.js.org/routes/request Demonstrates how to retrieve cookies, such as 'userId', from an incoming request in Nanoexpress.js. Cookies are frequently used for session management and user tracking. ```javascript app.post('/user', async (req) => { const { userId } = req.cookies; // You can use db.createUser(req.body), but this may cause side-effects const isUserLoggedIn = await dbHelper.checkUser(userId); // do something... }); ``` -------------------------------- ### Set Not Found Handler in Nanoexpress.js Source: https://nanoexpress.js.org/routes/errors-handling Configures a handler for requests that do not match any defined routes. This function is invoked when no route is found for the incoming request, providing a custom response for such cases. ```typescript app.setNotFoundHandler((req: HttpRequest, res: HttpResponse): HttpResponse => { return res.send({ code: 404, message: 'You entered wrong url' }); }); ``` -------------------------------- ### Accessing Request Headers in JavaScript Source: https://nanoexpress.js.org/routes/request Demonstrates how to access request headers, specifically the 'authorization' header, within a Nanoexpress.js route handler. This is commonly used for authentication purposes. ```javascript app.get('/secret', (req) => { const { authorization } = req.headers; }); ``` -------------------------------- ### Request Query Source: https://nanoexpress.js.org/routes/request Access query parameters from the URL to filter or modify requests, commonly used for search terms or pagination. ```APIDOC ## GET /user ### Description Retrieves user information, potentially filtered by a token provided in the query string. ### Method GET ### Endpoint `/user` ### Parameters #### Path Parameters None #### Query Parameters - **token** (string) - Required - A token used for verification or authentication. #### Request Body None ### Request Example ```javascript // /user?token=123 app.get('/user', async (req) => { const { token } = req.query; const result = await jwt.verifyToken(token); // do something... }); ``` ### Response #### Success Response (200) - **data** (any) - The data returned based on the query parameters. #### Response Example ```json { "data": "User details retrieved successfully" } ``` ``` -------------------------------- ### Request Headers Source: https://nanoexpress.js.org/routes/request Access request headers to retrieve information like authorization tokens or content types sent by the client. ```APIDOC ## GET /secret ### Description Retrieves sensitive information using the Authorization header. ### Method GET ### Endpoint `/secret` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript app.get('/secret', (req) => { const { authorization } = req.headers; }); ``` ### Response #### Success Response (200) - **authorization** (string) - The authorization token sent in the request headers. #### Response Example ```json { "message": "Access granted" } ``` ``` -------------------------------- ### Error Handling API Source: https://nanoexpress.js.org/routes/errors-handling This section details how to set a custom error handler for your Nano Express JS application. It allows you to intercept and manage errors that occur during request processing. Note that only async route functions and middlewares are handled. ```APIDOC ## POST /error-route ### Description Sets a custom error handler for the application. This function will be called when an error occurs during request processing. ### Method POST ### Endpoint /error-route ### Parameters #### Query Parameters - **err** (Error) - Required - The error object that occurred. - **req** (HttpRequest) - Required - The incoming request object. - **res** (HttpResponse) - Required - The outgoing response object. ### Request Body ```json { "status": "error", "status_code": 500, "message": "oops" } ``` ### Response #### Success Response (200) - **status** (string) - The status of the response, typically 'error'. - **status_code** (integer) - The HTTP status code, usually 500 for errors. - **message** (string) - A description of the error. #### Response Example ```json { "status": "error", "status_code": 500, "message": "oops" } ``` ``` -------------------------------- ### Request Validation Schema in JavaScript Source: https://nanoexpress.js.org/schemas Defines validation for request headers, disabling validation for query, params, and cookies. This leverages Ajv for validation. Incorrectly set validations (except body) can impact performance. ```javascript app.get( '/', { schema: { headers: { type: 'object', properties: { authorization: { type: 'string' } } }, query: false, params: false, cookies: false } }, async () => ({ hello: 'world' }) ); app.listen(4000); ``` -------------------------------- ### Validation Error Handler API Source: https://nanoexpress.js.org/routes/errors-handling Implement a custom handler for validation errors. This handler is invoked when data validation fails, allowing you to return specific error information to the client. Note: This feature is unavailable for the pro-slim version. ```APIDOC ## POST /validate-error ### Description Sets a custom handler for validation errors. This function will be called when data validation fails on incoming requests. ### Method POST ### Endpoint /validate-error ### Parameters #### Request Body - **foo** (string) - Optional - Example field for validation. ### Response #### Success Response (400) - **errors** (object) - An object containing validation error details. - **type** (string) - The type of error, e.g., 'errors'. - **errors** (array) - An array of specific error objects. - **body** (array) - An array of error messages related to the request body. #### Response Example ```json { "errors": { "type": "errors", "errors": [ { "body": ["type should be string, but got ..."] } ] } } ``` ``` -------------------------------- ### Request Body Source: https://nanoexpress.js.org/routes/request Process the request body to handle data submitted in POST or PUT requests, such as form data or JSON payloads. ```APIDOC ## POST /user ### Description Creates a new user with the provided username and password in the request body. ### Method POST ### Endpoint `/user` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The desired username for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```javascript app.post('/user', async (req) => { const { username, password } = req.body; const result = await db.createUser({ username, password }); // do something... }); ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating successful user creation. #### Response Example ```json { "message": "User created successfully" } ``` ``` -------------------------------- ### Request Cookies Source: https://nanoexpress.js.org/routes/request Access cookies sent by the client to manage session information or user preferences. ```APIDOC ## POST /user ### Description Checks if a user is logged in based on their userId cookie. ### Method POST ### Endpoint `/user` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **userId** (string) - Required - The ID of the user, typically stored in a cookie. ### Request Example ```javascript app.post('/user', async (req) => { const { userId } = req.cookies; const isUserLoggedIn = await dbHelper.checkUser(userId); // do something... }); ``` ### Response #### Success Response (200) - **isLoggedIn** (boolean) - Indicates whether the user is currently logged in. #### Response Example ```json { "isLoggedIn": true } ``` ``` -------------------------------- ### Set Validation Error Handler in Nanoexpress.js Source: https://nanoexpress.js.org/routes/errors-handling Sets a custom handler for validation errors. This is useful for providing detailed feedback to the client when request data fails validation. Note that this feature is unavailable in the 'pro-slim' version of Nanoexpress.js. ```typescript app.setValidationErrorHandler((errors: AjvValidationErrors[], req: HttpRequest, res: HttpResponse): HttpResponse => { return res.json({ errors }); }); ``` -------------------------------- ### Set Custom Error Handler in Nanoexpress.js Source: https://nanoexpress.js.org/routes/errors-handling Defines a custom error handler for asynchronous route functions and middlewares. It takes an error object, request, and response as input, allowing for custom error responses. Ensure your route functions are async for this handler to be effective. ```typescript app.setErrorHandler( (err: Error, req: HttpRequest, res: HttpResponse): HttpResponse => { if (checkSomething(err)) { return res.send({ status: 'error', status_code: 500, message: 'oops' }) } } ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.