HTTP Module
The http module provides both HTTP server and client funcality for building web applications and making HTTP requests.
HTTP Server
http.createServer()
Create an HTTP server:
let server = http.createServer();
server.on("GET", "/", func(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end("<h1>Hello, World!</h1>");
});
server.listen(3000);
print("Server running on http://localhost:3000");Route Handling
Handle different routes and methods:
let server = http.createServer();
//GET route
server.on("GET", "/", func(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end("<h1>Home Page</h1>");
});
// GET with path parameter
server.on("GET", "/about", func(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end("<h1>About Page</h1>");
});
// POST route
server.on("POST", "/api/data", func(req, res) {
let data = json.parse(req.body);
res.writeHead(200, {"Content-Type": "application/json"});
res.end(json.stringify({"received": true}));
});
server.listen(8080);JSON API
let server = http.createServer();
server.on("GET", "/api/users", func(req, res) {
let users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
];
res.writeHead(200, {"Content-Type": "application/json"});
res.end(json.stringify(users));
});
server.on("POST", "/api/users", func(req, res) {
let new_user = json.parse(req.body);
// Process new user...
res.writeHead(201, {"Content-Type": "application/json"});
res.end(json.stringify({"id": 3, "name": new_user["name"]}));
});
server.listen(3000);HTTP Client
http.get()
Make GET requests:
let response = http.get("https://api.example.com/data");
let data = json.parse(response);
print(data);http.post()
Make POST requests:
let payload = json.stringify({ name: "Alice", email: "alice@example.com" });
let response = http.post("https://api.example.com/users", payload);
print(response);Complete REST API Example
let server = http.createServer();
let users_db = [];
let next_id = 1;
// GET all users
server.on("GET", "/api/users", func(req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(json.stringify(users_db));
});
// POST create user
server.on("POST", "/api/users", func(req, res) {
let user_data = json.parse(req.body);
user_data["id"] = next_id;
next_id = next_id + 1;
users_db = push(users_db, user_data);
res.writeHead(201, {"Content-Type": "application/json"});
res.end(json.stringify(user_data));
});
// PUT update user
server.on("PUT", "/api/users", func(req, res) {
let updated_user = json.parse(req.body);
let user_id = updated_user["id"];
let i = 0;
while (i < len(users_db)) {
if (users_db[i]["id"] == user_id) {
users_db[i] = updated_user;
break;
}
i = i + 1;
}
res.writeHead(200, {"Content-Type": "application/json"});
res.end(json.stringify(updated_user));
});
// DELETE user
server.on("DELETE", "/api/users", func(req, res) {
let delete_data = json.parse(req.body);
let user_id = delete_data["id"];
// Remove user (simplified)
res.writeHead(200, {"Content-Type": "application/json"});
res.end(json.stringify({"deleted": true}));
});
server.listen(3000);Security Features
The HTTP server includes built-in security hardening:
let server = http.createServer();
// 1. Origin/Domain Filtering
server.setDevMode(true); // Auto-allow localhost (dev)
server.setAllowedOrigins(["example.com", "*.myapp.com"]);
server.addAllowedOrigin("api.trusted.io");
// 2. Rate Limiting (per IP)
server.setRateLimit(60); // 60 requests/minute per IP
// 3. Request Body Size Limit
server.setMaxBodySize(1048576); // 1MB max body size
// 4. CORS (Cross-Origin Resource Sharing)
server.enableCORS(true);
server.setCORSOrigins(["frontend.example.com", "*"]);
server.listen(3000);Security Method Reference
| Method | Description |
|---|---|
setDevMode(bool) | Allow localhost in development |
setAllowedOrigins(array) | Whitelist allowed origins |
addAllowedOrigin(string) | Add single origin to whitelist |
setRateLimit(int) | Requests per minute per IP |
setMaxBodySize(bytes) | Max request body size |
enableCORS(bool) | Enable CORS headers |
setCORSOrigins(array) | Allowed CORS origins |
HTTP Response Codes
403 Forbidden- Origin not allowed429 Too Many Requests- Rate limit exceeded413 Payload Too Large- Body size limit exceeded
Security Example
let server = http.createServer();
// Configure security
server.setDevMode(true); // Allow localhost in development
server.setAllowedOrigins(["myapp.com", "api.myapp.com"]);
server.setRateLimit(100); // 100 requests per minute
server.setMaxBodySize(2097152); // 2MB max body
server.enableCORS(true);
server.setCORSOrigins(["https://myapp.com"]);
server.on("GET", "/api/data", func(req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(json.stringify({"data": "secure"}));
});
server.listen(3000);Best Practices
- Always set appropriate
Content-Typeheaders - Use status codes correctly (200, 201, 404, 500, etc.)
- Parse JSON request bodies carefully
- Handle errors gracefully
- Keep the server running (blocking operation)
- Enable security features in production
- Configure rate limiting to prevent abuse
- Set appropriate body size limits
Next Steps
- JSON Module - Parse/stringify data
- SQLite Module - Add database to your API
- Auth Module - Secure your endpoints