// Node.js with TypeScript Example
// Import necessary modules from Node.js
import * as http from 'http';
import * as url from 'url';
// Define an interface for request handling
interface RequestHandler {
(req: http.IncomingMessage, res: http.ServerResponse): void;
}
// Create a simple HTTP server using the http module
const server: http.Server = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
// Parse the URL to get the pathname
const pathname: string = url.parse(req.url).pathname;
// Set response headers
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send a response based on the pathname
if (pathname === '/') {
res.end('Welcome to the homepage!');
} else if (pathname === '/about') {
res.end('This is the about page.');
} else {
res.end(`Page ${pathname} not found.`);
}
});
// Listen on port 3000
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
导入模块:我们使用 import
语句从 Node.js 标准库中导入了 http
和 url
模块。这些模块用于创建 HTTP 服务器和解析 URL。
定义接口:为了使代码更具类型安全性,我们定义了一个 RequestHandler
接口,它描述了请求处理函数的签名。
创建服务器:使用 http.createServer
方法创建了一个 HTTP 服务器,并传入一个请求处理函数。该函数接收两个参数:req
(请求对象)和 res
(响应对象)。
解析 URL:通过 url.parse
方法解析请求的 URL 并获取路径名。
设置响应头:使用 res.writeHead
方法设置响应的状态码和内容类型。
发送响应:根据不同的路径名发送不同的响应消息。
监听端口:最后,服务器监听 3000 端口,并在控制台输出启动信息。
这个示例展示了如何结合使用 Node.js 和 TypeScript 创建一个简单的 HTTP 服务器。
上一篇:js or
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站