分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

(转)NodeJS - 第一个应用程序Hello World

发布时间:2023-09-06 02:30责任编辑:赖小花关键词:Node

安装NodeJs

在创建实际的“Hello,World!”应用之前,我们应该先安装NodeJS,安装NodeJS可以访问NodeJS官网,下载相应系统的NodeJS的安装包,进行安装。


程序组件

关于Hello World 这个应用主要包括三部分组成

  • 导入所需的模块 
    -在程序中我们使用require指令来加载NodeJS模块

  • 创建服务器 
    -一个将监听类似于Apache HTTP Server的客户端请求的服务器。

  • 请求和响应 
    -在先前步骤中创建的服务器将读取由客户端(可以是浏览器或控制台)发出的HTTP请求并返回响应

创建NodeJS应用程序

第1步 - 导入所需模块 
我们使用require指令加载http模块并将返回的HTTP实例存储到http变量中,如下所示

var http = require("http");
  • 1

第2步 - 创建服务器 
我们使用创建的http实例并调用http.createServer()方法创建服务器实例,然后使用与服务器实例关联的listen方法将其绑定到端口3000 。通过参数请求和响应传递一个函数。编写样本实现以始终返回“Hello World”。

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(3000);// Console will print the messageconsole.log(‘Server running at http://127.0.0.1:3000/‘);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

第3步现在执行main.js来启动服务器

$ node main.js
  • 1

我们可以看到程序已经启动 
 
这时我们打开浏览器输入http://127.0.0.1:3000/ 可以看到: 

(转)NodeJS - 第一个应用程序Hello World

原文地址:https://www.cnblogs.com/xingchong/p/10291842.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved