网站首页 > 博客文章 正文
在创建实际的“ Hello,World!”之前 使用Node.js的应用程序,让我们看一下Node.js应用程序的组件。Node.js应用程序由以下三个重要组件组成-
- 导入所需的模块 -我们使用require指令加载Node.js模块。
- 创建服务器 -类似于Apache HTTP Server的服务器,它将监听客户端的请求。
- 读取请求并返回响应 -在先前步骤中创建的服务器将读取客户端(可以是浏览器或控制台)发出的HTTP请求并返回响应。
创建Node.js应用程序
步骤1-导入所需模块
我们使用require指令加载http模块并将返回的HTTP实例存储到http变量中,如下所示-
var http = require("http");
第2步-创建服务器
我们使用创建的http实例并调用http.createServer()方法来创建服务器实例,然后使用与服务器实例关联的listen方法将其绑定在端口8081上。将参数请求和响应传递给它。编写示例实现以始终返回“ Hello World”。
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
上面的代码足以创建一个HTTP服务器,该服务器进行侦听,即通过本地计算机上的8081端口等待请求。
第3步-测试请求和响应
让我们将第1步和第2步放到一个名为main.js的文件中,然后启动我们的HTTP服务器,如下所示-
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
现在执行main.js以启动服务器,如下所示:
$ node main.js
验证输出。服务器已启动。
Server running at http://127.0.0.1:8081/
向Node.js服务器发出请求
在任何浏览器中打开http://127.0.0.1:8081/,然后观察以下结果。
祝贺您,您的第一个HTTP服务器已启动并正在运行,它正在响应端口8081上的所有HTTP请求。
猜你喜欢
- 2024-09-15 python轻松抓取app接口(python抓app数据)
- 2024-09-15 spring boot 中设置 端口的 两种方式
- 2024-09-15 教你用 Python 操控你的上网请求(如何用python语言进行网络爬虫的开发)
- 2024-09-15 Linux(CentOS 7)下安装配置nginx代理多个tomcat实例和应用
- 2024-09-15 Iptables 最佳实践(iptables-j)
- 2024-09-15 nginx应用 | 反向代理,统一鉴权,目录重定向
- 2024-09-15 Docker-08-企业级私有仓库(k8s docker私有仓库搭建)
- 2024-09-15 Spring Boot中更改默认端口的方法
- 2024-09-15 Nginx基于TCP/UDP端口的四层负载均衡(stream模块)配置梳理
- 2024-09-15 RocketMQ 源码探究 —— 长连接与长轮询实现
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)