Node.js 学习系列(二) —— 创建一个应用

Node.js 应用由三部分组成:

(一)require 指令:

Node.js 中,使用 require 指令来加载和引入模块,引入的模块可以是内置模块,也可以是第三方模块或自定义模块。

语法格式:

const module = require('module-name');

module-name 可以是一个文件路径(相对或绝对路径),也可以是一个模块名称,如果是一个模块名称,Node.js 会自动从 node_modules 目录中查找该模块。

require 指令会返回被加载的模块的导出对象,可以通过该对象来访问模块中定义的属性和方法,如果模块中有多个导出对象,则可以使用解构赋值的方式来获取它们。

var http = require("http");

如上所示,使用 require 指令来载入 http 模块,并将实例化的 HTTP 赋值给变量 http

(二)创建服务器:

服务器可以监听客户端的请求,类似于 Apache 、NginxHTTP 服务器。

http.createServer(function (request, response) {
    
    
}).listen(6060 );

如上所示,使用 http.createServer() 方法创建服务器,向 createServer 函数传递了一个匿名函数,函数通过 request, response 参数来接收和响应数据,并使用 listen 方法绑定 6060 端口。

(三)接收请求与响应请求:

服务器很容易创建,客户端可以使用浏览器或终端发送 HTTP 请求,服务器接收请求后返回响应数据。

http.createServer(function (request, response) {
    
    
}).listen(6060 );

当回调启动,有两个参数被传入:requestresponse 。它们是对象,可以使用它们的方法来处理 HTTP 请求的细节,并且响应请求(例如:向发出请求的浏览器发回一些东西)。

现在,在 D:\demo\node 下新建一个 server.js 文件完成一个可以工作的 HTTP 服务器,代码如下:

// 请求(require)Node.js 自带的 http 模块,并且把它赋值给 http 变量
var http = require('http');
const hostname = '127.0.0.1';
const port = 6060;
// 调用 http 模块提供的函数: createServer 。这个函数会返回一个对象,这个对象有一个叫做 listen 的方法,这个方法有一个数值参数, 指定这个 HTTP 服务器监听的端口号
http.createServer(function (request, response) {
    
    
	console.log("Request received.");
    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    // 当收到请求时,使用 response.writeHead() 函数发送一个HTTP状态200和HTTP头的内容类型(content-type)
    response.writeHead(200, {
    
    'Content-Type': 'text/plain'});
    // 使用 response.write() 函数在HTTP相应主体中发送文本“response message:"
    response.write("response message:");
    // 调用 response.end() 发送响应数据 "Hello World" 完成响应
    response.end('Hello World!\n');
}).listen(port);

// 终端打印如下信息
console.log(`Server running at http://${
      
      hostname}:${
      
      port}/`);

使用 node 命令运行代码:
在这里插入图片描述

打开浏览器访问 http://localhost:6060/,可以看到页面效果如下:
在这里插入图片描述

(注意,当在服务器访问网页时,服务器可能会输出两次“Request received.”。是因为大部分服务器都会在访问 http://localhost:6060/ 时尝试读取 http://localhost:6060/favicon.ico )

猜你喜欢

转载自blog.csdn.net/HH18700418030/article/details/130618696
今日推荐