Home  >  Article  >  Web Front-end  >  A brief introduction to getting started with Node.js and Express (pictures and text)

A brief introduction to getting started with Node.js and Express (pictures and text)

黄舟
黄舟Original
2017-03-25 14:39:221534browse

This article mainly introduces www.php.cn/wiki/1498.html" target="_blank">A simple introduction to Node.js and Express, and details how to build a web server with Node.js and Express , if you are interested, you can learn about it

It’s just an introduction to how to build a web server with Node.js and Express, it doesn’t explain too many conceptual things. , Introduction to Nodejs

==Node is the server running environment for the Javascript

language ==

The so-called "running environment." "It has two meanings: first, the Javascript language runs on the server through Node. In this sense, Node is a bit like a Javascript virtual machine; second, Node provides a large number of tool libraries that enable the Javascript language to interact with the operating system (such as reading and writing files, creating new Subprocess), in this sense, Node is also a tool library for Javascript. Node uses Google's V8 engine internally as the Javascript language interpreter; it calls operating system resources through the self-developed libuv library.

2. Node.js download and installation

2.1 Node.js downloadThe official website will download and install Node.js according to your current Operating system, provide you with the most suitable version to download


##2.2 Installation

After successful download, there will be an msi file, double-click it to install. Yes. After the installation is successful, the corresponding environment variables A brief introduction to getting started with Node.js and Express (pictures and text) will be automatically configured, and we do not need to manually configure

## to install successfully. 2.3 Test whether Node.js is installed successfully

After the installation is successful, you can check whether the installation is successful in the window console. A brief introduction to getting started with Node.js and Express (pictures and text)

Enter the following command to check the node version.

node -v

Enter node directly and press Enter to let node execute our js code

node

##2.4 Use Node.js to run Javascript code#.

##Create a nodeproject directory and create a js file. 01_hello.js

var num1 = 10;
var num2 = 20;
console.log(num1 + num2);

In the windows console, switch to the directory where the js file is located and enter

A brief introduction to getting started with Node.js and Express (pictures and text)node. 01_hello.js

3. Clarification of some basic concepts in Node.js

3.1 Node.js is not a JS application, but a JS running platformA brief introduction to getting started with Node.js and Express (pictures and text)

Seeing the name Node.js, beginners may mistakenly think that it is a Javascript application. In fact, Node.js is written in C++ language. Cheng is a Javascript running environment.

Since it is not a Javascript application, why is it called .js? Because Node.js is a Javascript running environment. When it comes to Javascript, the first thing that comes to mind is the browser you use every day. Modern browsers include various components, including rendering engines, Javascript engines, etc. The Javascript engine is responsible for interpreting and executing the Javascript code in web pages. As one of the most important languages ​​for the Web front-end, Javascript has always been the patent of front-end engineers. However, Node.js is a back-end Javascript running environment (supported systems include Linux, Windows), which means you can write system-level or server-side Javascript code and leave it to Node.js for interpretation and execution ,

3.2 The relationship between Node.js and Javascript

Javascript includes 3 parts: ECMAscript-262, BOM, and DOM. The BOM is related to the browser, and the DOM is related to the HTML page. Node.js just includes ECMAscript-262. Therefore, some of our previous operations on BOM and DOM were run on the browser side and cannot be used in Node.js.

3.3 Several global variables in Node.js

global:

represents the global environment where Node is located , similar to the browser's A brief introduction to getting started with Node.js and Express (pictures and text)window object

. It should be noted that if you declare a global variable in the browser, you are actually declaring the

property

of a global object. For example, var x = 1 is equivalent to setting window.x = 1, but this is not the case with Node. , at least not in modules (the REPL environment
    behaves
  1. consistent with the browser). In the module file, declare var x = 1. This variable is not a property of the global object, and global.x is equal to undefined. This is because the global variables of the module are private to the module and cannot be accessed by other modules.

    process: This object represents the current process in which Node is located, allowing developers to interact with the process.

  2. console:指向Node内置的console模块,提供命令行环境中的标准输入、标准输出功能。

3.4 Node.js中的几个全局函数

  1. setTimeout():用于在指定毫秒之后,运行回调函数。实际的调用间隔,还取决于系统因素。间隔的毫秒数在1毫秒到2,147,483,647毫秒(约24.8天)之间。如果超过这个范围,会被自动改为1毫秒。该方法返回一个整数,代表这个新建定时器的编号。

  2. clearTimeout():用于终止一个setTimeout方法新建的定时器。

  3. setInterval():用于每隔一定毫秒调用回调函数。由于系统因素,可能无法保证每次调用之间正好间隔指定的毫秒数,但只会多于这个间隔,而不会少于它。指定的毫秒数必须是1到2,147,483,647(大约24.8天)之间的整数,如果超过这个范围,会被自动改为1毫秒。该方法返回一个整数,代表这个新建定时器的编号。

  4. clearInterval():终止一个用setInterval方法新建的定时器。

  5. require():用于加载模块。

  6. Buffer():用于操作二进制数据。

3.5 Node.js的核心模块

如果只是在服务器运行Javascript代码,用处并不大,因为服务器脚本语言已经有很多种了。Node.js的用处在于,它**本身**还提供了一系列功能模块,与操作系统互动。这些核心的功能模块,不用安装就可以使用,下面是它们的清单。

  1. http:提供HTTP服务器功能。

  2. url:解析URL。

  3. fs:与文件系统交互。

  4. querystring:解析URL的查询字符串。

  5. child_process:新建子进程。

  6. util:提供一系列实用小工具。

  7. path:处理文件路径。

  8. crypto:提供加密和解密功能,基本上是对OpenSSL的包装。

三、搭建web应用

使用Node.js搭建web服务器,一般使用一些框架来帮助完成。

express 是一个开源的node.js项目框架,初学者使用express可以快速的搭建一个Web项目,express中已经集成了Web的http服务器创建、请求和文件管理以及Session的处理等功能,所以express是非常适合初学者的入门学习。

3.1 安装Express框架

使用node.js自带的包管理器npm安装。

创建一个项目目录,Node_Hello。进入该目录,创建一个package.json文件,文件内容如下:

{
 "name": "Node_Hello",
 "description": "nodejs hello world app",
 "version": "0.0.1",
 "private": true,
 "dependencies": {
  "express": "4.x"
 }
}

 上面代码定义了项目的名称、描述、版本等,并且指定需要4.0版本以上的Express。

==从控制台首先进入刚才的项目目录==,然后输入如下命令,则会开始下载Express。

npm install

A brief introduction to getting started with Node.js and Express (pictures and text)

下载完成

A brief introduction to getting started with Node.js and Express (pictures and text)

A brief introduction to getting started with Node.js and Express (pictures and text)

3.2 创建启动文件

在上面的项目目录下,新建一个启动文件,名字暂叫 ==index.js== 。书写如下代码:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
 res.send(&#39;<h1>你好,这是我们的第一个nodejs项目</h1>&#39;);
});
app.listen(8080);

 3.3 运行index.js文件

node index.js

3.4 使用浏览器访问

在浏览器输入下面的地址就可以访问我们刚刚搭建的web网站了。

127.0.0.1:8080

四、使用Webstorm搭建Node.js web应用

使用webstorm搭建Node.js应用更加方便。

4.1 下载WebStorm,并安装

下载完成后,直接安装即可。

4.2 创建Node + Express应用

A brief introduction to getting started with Node.js and Express (pictures and text)

4.3 Project目录结构

A brief introduction to getting started with Node.js and Express (pictures and text)

app.js:启动文件,或者说入口文件

package.json:存储着工程的信息及模块依赖,当在 dependencies 中添加依赖的模块时,运行 npm install ,npm 会检查当前目录下的 package.json,并自动安装所有指定的模块

node_modules:存放 package.json 中安装的模块,当你在 package.json 添加依赖的模块并安装后,存放在这个文件夹下

public:存放 image、css、js 等文件

routes:存放路由文件

views:存放视图文件或者说模版文件

bin:存放可执行文件(www)

 4.4 各个主要文件的说明

4.4.1 app.js

//加载模块
var express = require(&#39;express&#39;);
var path = require(&#39;path&#39;);
var favicon = require(&#39;serve-favicon&#39;);
var logger = require(&#39;morgan&#39;);
var cookieParser = require(&#39;cookie-parser&#39;);
var bodyParser = require(&#39;body-parser&#39;);
//加载路由文件
var index = require(&#39;./routes/index&#39;);
var users = require(&#39;./routes/users&#39;);

// 生产一个express的实例
var app = express();

// view engine setup
/*
设置 views 文件夹为存放视图文件的目录,
即存放模板文件的地方,dirname 为全局变量,
存储当前正在执行的脚本所在的目录。
 */
app.set(&#39;views&#39;, path.join(dirname, &#39;views&#39;));
//设置模板引擎为ejs
app.set(&#39;view engine&#39;, &#39;ejs&#39;);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(dirname, &#39;public&#39;, &#39;favicon.ico&#39;)));
//加载日志中间件
app.use(logger(&#39;dev&#39;));
//加载解析json的中间件
app.use(bodyParser.json());
//加载解析urlencoded请求体的中间件。 post请求
app.use(bodyParser.urlencoded({extended: false}));
//加载解析cookie的中间件
app.use(cookieParser());
//设置public文件夹为放置静态文件的目录
app.use(express.static(path.join(dirname, &#39;public&#39;)));

// 路由控制器。
app.use(&#39;/&#39;, index); // http://localhost:3000
app.use(&#39;/users&#39;, users);  //http://localhost:3000/users


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error(&#39;Not Found&#39;);
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get(&#39;env&#39;) === &#39;development&#39; ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render(&#39;error&#39;);
});

//把app导出。 别的地方就可以通过 require("app") 获取到这个对象
module.exports = app;

 4.4.2 bin/www

#!/usr/bin/env node //表明是node可执行文件

/**
 * Module dependencies.
 */
//引入我们在app.js中导出的app模块
var app = require(&#39;../app&#39;);
//引入debuger模块,打印调试日志
var debug = require(&#39;debug&#39;)(&#39;hello:server&#39;);
//引入http模块
var http = require(&#39;http&#39;);

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || &#39;3000&#39;);
app.set(&#39;port&#39;, port); //设置端口号

/**
 * Create HTTP server.
 */
//创建Http服务器
var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
//监听指定的端口
server.listen(port);
//监听error事件。 onError是发生错误的时候的回调函数
server.on(&#39;error&#39;, onError);
//监听listening事件
server.on(&#39;listening&#39;, onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
 var port = parseInt(val, 10);

 if (isNaN(port)) {
  // named pipe
  return val;
 }

 if (port >= 0) {
  // port number
  return port;
 }

 return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
 if (error.syscall !== &#39;listen&#39;) {
  throw error;
 }

 var bind = typeof port === &#39;string&#39;
  ? &#39;Pipe &#39; + port
  : &#39;Port &#39; + port;

 // handle specific listen errors with friendly messages
 switch (error.code) {
  case &#39;EACCES&#39;:
   console.error(bind + &#39; requires elevated privileges&#39;);
   process.exit(1);
   break;
  case &#39;EADDRINUSE&#39;:
   console.error(bind + &#39; is already in use&#39;);
   process.exit(1);
   break;
  default:
   throw error;
 }
}
/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
 var addr = server.address();
 var bind = typeof addr === &#39;string&#39;
  ? &#39;pipe &#39; + addr
  : &#39;port &#39; + addr.port;
 debug(&#39;Listening on &#39; + bind);
}

4.4.3 routes/index.js

var express = require(&#39;express&#39;);
var router = express.Router();

/* GET home page. */
router.get(&#39;/&#39;, function(req, res, next) {
 res.render(&#39;index&#39;, { title: &#39;育知同创&#39; });
});

module.exports = router;
/*
 生成一个路由实例用来捕获访问主页的GET请求,
 导出这个路由并在app.js中通过app.use(&#39;/&#39;, routes);
 加载。这样,当访问主页时,就会调用res.render(&#39;index&#39;, { title: &#39;育知同创&#39; });
 渲染views/index.ejs模版并显示到浏览器中。
 */

 4.4.4 对路由写法的优化

在前面的==app.js中==,每个模板都有添加一次路由比较麻烦,其实应该把添加路由的事情专门交给index.js来做。也就是可以把多个路由放在一个路由文件中。

//加载路由文件
var index = require(&#39;./routes/index&#39;); //去掉
var users = require(&#39;./routes/users&#39;); //去掉
// 路由控制器。
app.use(&#39;/&#39;, index); // http://localhost:3000 //去掉
app.use(&#39;/users&#39;, users);  //http://localhost:3000/users  //去掉

 可以改成:

var routes = require(&#39;./routes/index&#39;);
routes(app);

==index.js==文件优化成: 这样管理起来就方便很多

module.exports = function (app) {
 //一个get请求的路由 http://localhost:3000
 app.get("/", function (req, res) {
   res.render("index", {title:"育知同创abc"})
 });
 //又一个请求路由:http://localhost:3000/abc
 app.get("/abc", function (req, res) {
   res.render("index", {title:"育知同创" + req.path})
 });
}

4.4.5 ejs模板

模板引擎(Template Engine)是一个将页面模板和要显示的数据结合起来生成 HTML 页面的工具。如果说上面讲到的 express 中的路由控制方法相当于 MVC 中的控制器的话,那模板引擎就相当于 MVC 中的视图。

模板引擎的功能是将页面模板和要显示的数据结合起来生成 HTML 页面。它既可以运 行在服务器端又可以运行在客户端,大多数时候它都在服务器端直接被解析为 HTML,解析完成后再传输给客户端,因此客户端甚至无法判断页面是否是模板引擎生成的。有时候模板引擎也可以运行在客户端,即浏览器中,典型的代表就是 XSLT,它以 XML 为输入,在客户端生成 HTML 页面。但是由于浏览器兼容性问题,XSLT 并不是很流行。目前的主流还是由服务器运行模板引擎。

在 MVC 架构中,模板引擎包含在服务器端。控制器得到用户请求后,从模型获取数据,调用模板引擎。模板引擎以数据和页面模板为输入,生成 HTML 页面,然后返回给控制器,由控制器交回客户端。

==ejs 是模板引擎的一种,它使用起来十分简单,而且与 express 集成良好。==

我们通过以下两行代码设置了模板文件的存储位置和使用的模板引擎:(app.js文件中进行的设置)

app.set(&#39;views&#39;, dirname + &#39;/views&#39;);
app.set(&#39;view engine&#39;, &#39;ejs&#39;);
<!DOCTYPE html>
<html>
 <head>
  <title><%= title %></title>
  <link rel=&#39;stylesheet&#39; href=&#39;/stylesheets/style.css&#39; />
 </head>
 <body>
  <h1><%= title %></h1>
  <p>Welcome to <%- title %></p>
 </body>
</html>

说明:

ejs 的标签系统非常简单,它只有以下三种标签:

  1. 09ec39c8cf80993cee8f36d507abec3c:Javascript 代码。

  2. b87f5fe9deb6bc8214cf0c7085055a22:显示替换过 HTML 特殊字符的内容。(也就是说如果code中有标签,则会原样输出,不会让浏览器解析)

  3. 8c0f8149cd2243ceacec364b0951d5dd:显示原始 HTML 内容。(如果有a标签,在浏览器端这则会看到一个超链接)

路由代码:

router.get(&#39;/&#39;, function(req, res, next) {
 res.render(&#39;index&#39;, { title: "<a href=&#39;http://www.baidu.com&#39;>百度 </a>"});
});

// 则会用title的值去替换ejs中的相应的代码。

则生成的代码:

<!DOCTYPE html>
<html>
 <head>
  <title><a href=&#39;http://www.baidu.com&#39;>百度 </a></title>
  <link rel=&#39;stylesheet&#39; href=&#39;/stylesheets/style.css&#39; />
 </head>
 <body>
  <h1><a href=&#39;http://www.baidu.com&#39;>百度 </a></h1>
  <p>Welcome to <a href=&#39;http://www.baidu.com&#39;>百度 </a></p>
 </body>
</html>

The above is the detailed content of A brief introduction to getting started with Node.js and Express (pictures and text). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn