Types के साथ HTTP Module
In this page:
import * as http from "http";
const server = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
res.end("text");
});
server.listen(port);
एक HTTP Server बनाना
Node के built-in http module और @types/node से एक HTTP server बनाना createServer callback को correctly typed IncomingMessage और ServerResponse parameters देता है, untyped raw objects के बजाय।
उदाहरण: Creating an HTTP Server
// import * as http from "http";
// const server = http.createServer((req, res) => { res.end("ok"); });
console.log("createServer's callback receives typed IncomingMessage/ServerResponse");
Incoming Requests को Type करना
Incoming requests को type करने का मतलब है IncomingMessage की .url और .method जैसी properties उपयोग करना, दोनों possibly undefined typed हैं, correctly यह reflect करते हुए कि एक malformed raw HTTP request उन्हें omit कर सकता है।
उदाहरण: Typing Incoming Requests
// (req: http.IncomingMessage) => {
// const url: string | undefined = req.url;
// const method: string | undefined = req.method;
// }
console.log("req.url and req.method are typed as possibly undefined");
Types के साथ Routing
Types के साथ routing typically req.method और req.url पर narrowed string comparisons के साथ switch करना है, क्योंकि built-in http module का अपना कोई router नहीं है — कोई भी routing structure कुछ ऐसा है जिसे आप खुद type करते हैं।
उदाहरण: Routing with Types
function route(method: string, url: string): string {
if (method === "GET" && url === "/") return "home";
return "not found";
}
console.log(route("GET", "/"));
Typed JSON Responses
एक typed JSON response भेजने का मतलब है res.end(JSON.stringify(data)) call करना जहां data का shape एक interface से defined है, इसलिए एक response field name में typo client तक पहुंचने से पहले ही पकड़ लिया जाता है।
उदाहरण: Typed JSON Responses
interface ApiResponse { status: string }
const data: ApiResponse = { status: "ok" };
// res.end(JSON.stringify(data));
console.log(JSON.stringify(data));
Typed Server Configuration
Typed server configuration — जैसे port number या createServer/listen को pass किए TLS options — basic mistakes पकड़ता है जैसे जहां असल में एक ListenOptions object या number expected हो वहां एक string pass करना।
उदाहरण: Typed Server Configuration
interface ListenOptions { port: number; host?: string }
const options: ListenOptions = { port: 8080 };
// server.listen(options.port);
console.log("Listening on port", options.port);
- बिना check किए
req.url.split("?")उपयोग करना, जबreq.urlstring | undefinedtyped है। res.end()call करना भूल जाना, इसलिए request hang हो जाती है।Content-Type: application/jsonset किए बिना JSON भेजना, इसलिए clients इसे सही से parse नहीं करते।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: