赞
踩
Nodejs 带有许多内置的核心模块和实用程序。这些可以帮助您创建应用程序,但这将是费力和困难的。因此,我们有一个很好的选择,那就是 Express js 框架,它建立在 http 核心模块之上,为我们提供了许多方便的功能和实用程序,使开发过程比以往任何时候都更简单、更快捷。
您需要具备以下先决条件才能阅读本文:
Express js 框架体积小、开源、免费,于 2010 年发布。从技术上讲,express 是在 Node js 核心模块 http 的帮助下构建的,使开发周期更省时、更轻松。它本质上是用于 Node js 服务器(后端和 API 服务)开发的标准框架,目前版本为 4.0,版本 5.0 处于 beta 测试阶段。
Express 通过使用 Node.js 的核心模块,为您提供了一组实用程序,包括处理程序、路由器、控制器、中间件等。此外,对如何使用这些实用程序创建后端服务没有限制。因此,快速框架提供了有效启动开发过程所需的一切。
与其他后端服务相比,使用 Express 的一些优点是:
Nodejs 示例:
- // requiring the core http module
- const http = require('http');
-
- // creating server object
- const server = http.createServer((req, res) => {
- const url = req.url;
-
- // routing is not provided in nodejs hence checking for the URL of the request while sending the response
- if(url === '/') {
- res.write('<html>');
- res.write('<head><h1>Scaler Topics</h1><head>');
- res.write('<body><h2>Hello from Nodejs express framework example !!</h2></body>');
- res.write('</html>');
- return res.end();
- }
-
- // routing is not provided in nodejs hence checking for the URL of the requrest while sending the response
- if(url === '/about') {
- res.write('<html>');
- res.write('<head><h1>Scaler Topics</h1><head>');
- res.write('<body><h2>Nodesjs does not provide us with routing !!</h2></body>');
- res.write('</html>');
- return res.end();
- }
- });
-
- // setting up the server
- server.listen(3000, () => {
- console.log("Starting the server on port 3000")
- });

Nodejs Express 示例
- // requiring express module
- const express = require('express');
-
- // creating an app using express instance
- const app = express();
-
- // handling '/' request
- app.get('/', (req, res) => {
- res.send('<h1>Scaler Topics</h1>');
- });
-
- // handling '/about' request
- app.get('/about', (req,res) => {
- res.send('<h1>Hello from Nodejs Express framework example !!</h1>');
- });
-
- // setting up the server
- app.listen(8080, () => {
- console.log('Starting the server on port 3000');
- });
'运行
现在,我们已经了解了 express 及其重要性,让我们开始使用 nodejs express。第一步是安装 express。按照以下步骤在您的系统中安装 express:
mkdir express-app
现在导航到创建的目录:
cd express-app
npm init
上述命令用于初始化Node.js项目。将提出有关该项目的一系列问题。之后,将创建一个包含有关项目信息的package.json文件。
npm install express
上面的命令将安装 express。完成后将创建一个node_modules文件夹。package.json 文件将具有依赖项中提到的 express 及其版本。
安装 express 后,让我们创建一个小型 express 应用程序。 在项目目录下创建一个server.js文件,并在其中编写以下代码:
- // require express module
- const express = require('express')
-
- // creating an app using express instance
- const app = express()
-
- // Setting app PORT as 8080.
- const PORT = 8080
-
- // Create a get endpoint at baseURL.
- app.get('/', (req, res) => {
- res.send('Hello World!!')
- })
-
- // Make the app listen on the specified port
- app.listen(PORT, () => {
- console.log(`Express app listening on port ${PORT}`)
- })

现在保存文件并执行以下命令以运行代码:
node server.js
当应用程序启动时,您将在终端中收到以下消息:
Express app listening on port 8080
现在在 Web 浏览器中打开 localhost:8080,您将看到以下输出:
模块是一段封装的代码,我们可以将其导入到项目其他部分的任何位置。可以在 require() 函数的帮助下导入模块。
语法如下所示
const moduleName = require(‘module-name’)
Express 是第三方模块
- const express = require("express");
- const app = express();
首先,我们必须导入模块,然后调用返回的对象来创建快速应用程序。
我们同样可以导入其他模块:
- var mongoose = require("mongoose");
- var fs = require("fs");
我们还可以创建模块并以类似的方式导入它们。要导出函数或变量,我们必须使用 exports 对象。exports 对象是对 module.exports 的引用,其中 module 是全局的。语法如下:
- exports.<module_name / variable_name / function_name > = <module_name / variable_name / function_name >`
让我们创建一个文件util.js并在文件中导出一组函数:
- function createUser(userInfo){
- validate(userInfo)
- //connect to db and process user registration.
- }
-
- function validate(userInfo){
- // Code for validating user info and returning errors if any
- }
-
- function login(userCredentials){
- // Code for validating user info and
- //Handling user login if credentials are right
- }
-
-
- exports.createUser = createUser
- exports.validate = validate
- exports.login = login
'运行
我们现在可以将函数导入到任何其他文件中,如下所示:
- // If util.js and the current file are in the same directory.
- const { createUser, validate, login } = require("./util")
现在,所有这些函数都可以在当前文件中使用。
express Request 对象表示 HTTP 请求,并具有查询字符串、正文、标头等属性。响应对象表示 HTTP 响应。它用于将响应发送回浏览器或在客户端的浏览器中添加 cookie 值。
例:
- var express = require("express");
- var app = express();
- var PORT = 8080;
- bodyParser = require("body-parser");
-
- // support parsing of application/json type post data
- const urlEncParser = bodyParser.urlencoded({ extended: true });
-
- // Use of middleware to parse the body of the request in JSON form.
- app.post("/form", urlEncParser, (req, res) => {
- // Print the body of request
- console.log("Body : ", req.body);
-
- // Print the Headers of request
- console.log("Headers : ", req.headers);
-
- // Print the Query String of request
- console.log("Query String : ", req.query);
-
- // Print the path of request
- console.log("Path : ", req.path);
-
- // Print the cookie data sent with request
- console.log("Cookies : ", req.cookies);
-
- // Get the firstname and lastname from the body of the request and combine them and send them as fullname
- const data = {
- fullname: req.body.firstname + " " + req.body.lastname,
- };
-
- // Add cookie info in the user's browser.
- res.cookie("Info", { SampleKey: "Sample data" });
-
- // Send the response using res.send() method.
- res.send(JSON.stringify(data));
- });
-
- app.listen(PORT, function (err) {
- if (err) console.log(err);
- console.log(`Server listening on PORT: ${PORT}`);
- });

输出:
Server listening on PORT: 8080 Body: { firstname: 'John', lastname: 'Doe' } Headers: { host: '127.0.0.1:8080', connection: 'keep-alive', 'content-length': '27', 'cache-control': 'max-age=0', ... origin: 'null', 'content-type': 'application/x-www-form-urlencoded', ... cookie: undefined, 'if-none-match': 'W/"17-1+uiygXxvKCInIP4KZEKUIq9o6Q"' } Query String: {} Path: /form Cookies: undefined
路由定义了应用程序如何响应特定路径(或 URI)上的 HTTP 请求方法(GET、POST 等)。每个路由都与一个或多个处理程序函数相关联。处理程序函数用于定义该路由的逻辑。
路由的定义可以概括如下:
app.METHOD( route_path, handler_function )
以上代码说明:
让我们看一些例子:
位于 / 路由的 GET 请求的终结点。
- app.get('/', ( req, res ) => {
- res.send(' Get request at / path ')
- })
/user 路由中 POST 请求的终结点。
- app.post('/user', ( req, res ) => {
- res.send(' POST request at /user ')
- })
/user 路由中 PUT 请求的终结点。
- app.put('/user', ( req, res ) => {
- res.send(' PUT request at /user ')
- })
/user 路由中 DELETE 请求的终结点。
- app.delete('/user', ( req, res ) => {
- res.send(' DELETE request at /user ')
- })
在同步操作中,主线程的执行将被阻止,直到操作完成。仅当电流完成时,下一个操作才会开始。
- console.log(" Statement 1 ");
- console.log(" Statement 2 ");
例如,在上面的代码中,第一个 console.log() 将执行,之后第二个将执行。
在异步 API 中,操作放置在事件队列中,并且主线程不会被阻塞。这样,就可以处理异步 API。这加快了应用程序的速度,也提高了效率。如果我们将第一个 console.log() 放在 setTimeout() 函数中,输出将被反转:
- setTimeout( () =>
- console.log(" Statement 1 "),
- 1000);
-
- console.log("Statement 2");
输出:
- Statement 2
- Statement 1
我们可以使用 async await 或 promise 来处理异步操作。让我们看一下使用 promise 处理异步代码的处理函数。
- app.get('/', function( req, res ) {
- // query some data from the database
- queryDB()
- .then(function (data) {
- // handle data
- return OperationA(data)
- })
- .then(function (res) {
- // handle res
- })
- })
在上面的代码片段中,假设 queryDB() 是一个使用从数据库查询数据的函数,完成此操作后,将调用 .then 处理程序并接收 queryDB() 的输出。这在承诺链上进一步延伸。
完成上述操作的另一种方法是使用 async-await,我们可以使函数异步并使用 await 完成 promise。
让我们来看看。
- app.get('/',async function (req, res) {
- // query some data from the database
- const data = await queryDB()
- const res = await OperationA(data)
- // handle res
- });
静态文件(如图像、html 文件或其他媒体)可以使用 express 中间件 express.static() 提供。使用此中间件的语法是:
express.static(root, [options])
其中 root 是包含静态文件的文件夹的路径,选项是具有各种属性(如 setHeaders、dotfiles 等)的对象。
假设您想在目录 public 中提供静态文件。您必须添加:
app.use(express.static('public'))
这些文件在基 URL 中提供,并结合了文件相对于静态文件文件夹的路径。
例如,如果图像sample.png存储在静态文件文件夹中,则可以在以下位置访问它:
本地主机:8080/sample.png
如果 CSS 文件位于 static/style 文件夹中,则:
本地主机:8080/style/styles.css
我们可以对多个文件夹多次使用 express.static()。如果在第一个文件夹中找不到文件,则将执行第二个中间件。
我们还可以创建一个虚拟前缀,例如:
app.use(‘/file’ , express.static('public'))
'运行
现在,静态文件将位于 /file 路径中。
为了处理错误,使用了具有四个参数的中间件函数。这四个参数是:err(错误)、req(请求)、res(响应)和 next(下一个中间件函数)。
- app.use(function (err, req, res, next) {
- console.error( err );
- res.status(500).send(" Server Error !!! ");
- });
这个中间件应该在所有路由和其他中间件之后使用,这样如果没有中间件可以处理请求,那么错误就会被处理。
Express 还具有内置的错误处理程序。如果所描述的中间件都无法处理错误,则 express 内置处理程序会将错误消息发送给带有堆栈跟踪的 fluent。
HTTP Get 方法用于从服务器获取资源。它可以将有限数量的数据作为 URL 参数传递。让我们在 express 的帮助下使用 GET 方法。
在server.js文件中,编写以下代码:
- // requiring express and creating an app using express instance
- var express = require("express");
- var app = express();
- var PORT = 8080;
-
- app.get("/form", ( req, res ) => {
- // Get the firstname and lastname as query parameters and combine them and send them as fullname
- const data = {
- fullname: req.query.firstname + " " + req.query.lastname,
- };
-
- console.log(data);
- // Send response
- res.send(JSON.stringify(data));
- });
-
- app.listen(PORT, function (err) {
- if (err) {
- console.log(err);
- }
- console.log(` Server listening on PORT: ${PORT} `);
- });

创建一个文件form.html以制作一个小表单,如下所示:
- <!DOCTYPE html>
- <html>
- <body>
- <form action="http://127.0.0.1:8080/form" method="GET">
- Write your First Name: <input type="text" name="firstname" />
- <br />
- Write your Last Name: <input type="text" name="lastname" />
- <input type="submit" value="Submit" />
- </form>
- </body>
- </html>
form.html的输出如下所示:
按提交后,网页将显示以下响应:
服务器控制台将显示以下内容:
- $ node server.js
- Server listening on PORT 8080
- { fullname : 'John Doe'}
在上面的代码中,firstname 和 lastname 作为查询参数传递,请求由 get 端点处理。处理程序函数以全名形式提供响应。
POST 方法用于在请求正文中发送大量数据。数据也是安全的,因为它在 URL 中不可见。
现在让我们在 POST 的帮助下实现相同的示例。
在server.js文件中编写以下代码。
- // requiring express and creating an app using express instance
- var express = require("express");
- var app = express();
- var PORT = 8080;
-
- // requiring body-parser
- bodyParser = require("body-parser");
-
- // support parsing of application/json type post data
- const urlEncParser = bodyParser.urlencoded({ extended: true });
-
- // Use of middleware to parse the body of the request in JSON form.
- app.post("/form", urlEncParser, (req, res) => {
- console.log(req.body);
- // Get the firstname and lastname from the body of the request and combine them and send them as fullname
- const data = {
- fullname: req.body.firstname + " " + req.body.lastname,
- };
-
- console.log(data);
- res.send(JSON.stringify(data));
- });
-
- app.listen(PORT, function (err) {
- if (err) {
- console.log(err);
- }
- console.log(`Server listening on PORT: ${PORT}`);
- });

在form.html中进行更改,如下所示:
- <!DOCTYPE html>
- <html>
- <body>
- <form action="http://127.0.0.1:8080/form" method="POST">
- Write your First Name: <input type="text" name="firstname" />
- <br />
- Write your Last Name: <input type="text" name="lastname" />
- <input type="submit" value="Submit" />
- </form>
- </body>
- </html>
上面的代码将提供与 GET 类似的输出,只是数据在 URL 中不可见。
让我们看看如何使用 POST 方法上传文件。index.html代码如下:
<html> <head> <title>File Uploading Tutorial</title> </head> <body> <h1>File Upload:</h1> Select the file to upload: <br /> <form action = "http://127.0.0.1:8081/file_upload" method = "POST" enctype = "multipart/form-data"> <input name="file" type="file" size="100" /> <br /> <input type = "submit" value = "Upload File" /> </form> </body> </html>
现在,让我们修改server.js以处理表单数据:
- // requiring the necessary modules
- var express = require('express');
- var app = express();
- var fs = require("fs");
-
- // body-parser will handle the JSON data
- var bodyParser = require('body-parser');
- var multer = require('multer');
-
- // including all the middlewares
- app.use(express.static('public'));
- app.use(bodyParser.urlencoded({ extended: false }));
- // specifing the destination folder of the files
- app.use(multer({ dest: '/tmp/'}));
-
- app.get('/index.htm', function (req, res) {
- res.sendFile( __dirname + "/" + "index.htm" );
- })
-
- // handling the POST request at /file_upload
- app.post('/file_upload', function (req, res) {
- var file = __dirname + "/" + req.files.file.name;
-
- fs.readFile( req.files.file.path, function (err, data) {
- fs.writeFile(file, data, function (err) {
- if( err ) {
- console.log( err );
- } else {
- response = {
- message:'File successfully uploaded',
- filename:req.files.file.name
- };
- }
-
- res.end( JSON.stringify( response ) );
- });
- });
- })
-
- var server = app.listen(8080, function (err) {
- if (err) {
- console.log(err);
- }
- console.log(`Server listening on PORT: ${PORT}`);
- })

现在您可以检查表格
http://127.0.0.1:8080/index.htm。
当用户浏览该网站时,存储在用户浏览器中的一小段数据称为 cookie。每次用户重新加载网站时,此数据都会发送回服务器,以区分用户以前的活动。我们使用 cookie-parser 包在 nodejs express 应用程序中使用 cookie。通过使用此软件包,我们可以顺利地管理cookie。
安装cookie管理包:
npm install cookie-parser
cookie-parser 的语法:
- app.get('/set_cookie_route', function( req, res ) {
- res.cookie(cookie_name , 'cookie_value').send('Cookie is set');
- });
在 nodejs express 应用程序中添加此中间件:
- // requiring the express and cookie-parser module
- const express = require('express');
- const cookieParser = require('cookie-parser');
-
- const app = express();
-
- // adding cookieParser to the middleware stack
- app.use(cookieParser());
上面的模块放弃了对 req.cookies 的访问,其中包含一个具有 cookie 名称及其属性的对象。
我们还可以使用 req.secret 通过传递密钥字符串来启用签名的支持 cookie。
设置 Cookie:
- app.get('/cookie_route', function(req, res) {
- // setting maxAge of cookie
- const time = 55 * 1000;
-
- res.cookie(cookie_name, 'cookie_value', { maxAge : minute });
-
- return res.send('Cookie has been set !!!');
- });
上面代码中使用的 maxAge 选项是可选的。让我们看看其他选项:
res.cookie(cookie_name, 'cookie_value', {expire : 24 * 60 * 60 * 1000 });
res.cookie(cookie_name, 'cookie_value', { HttpOnly : true});
res.cookie(cookie_name, 'cookie_value', { secure : true});
阅读 Cookie:
用户可以使用以下命令访问 cookie:req.cookies 或 req.cookies.cookie_name。
删除 Cookie:
我们可以简单地使用浏览器开发人员工具删除 cookie,也可以简单地使用 res.clearCookie() 方法。此函数接受单个参数,即要删除的 cookie 的名称。
- app.get('/delete_cookie_route', function(req, res) {
- res.clearCookie('cookie_name');
- res.send('Cookie is deleted');
- });
'运行
Nodejs Express 应用程序支持许多数据库服务,如 MongoDB、SQL、SQLite、PostgreSQL、Redis 等。Express 本身不会为数据库管理服务定义任何额外的特定条件或行为。数据库服务可以是基于云的,也可以存在于系统中的本地。若要使用上述服务提供商,需要安装其驱动程序,然后将应用与该数据库服务连接。
让我们以 MongoDB 连接为例。 安装MongoDB驱动程序:
npm install mongodb --save
现在让我们将数据库连接到您的 Nodejs express 应用程序:
- async function main() {
- const MongoClient = require('mongodb').MongoClient;
- const uri = 'mongodb+srv://dbUser:<dbpassword>@cluster0.dcu5m.mongodb.net/sample_airbnb?retryWrites=true&w=majority';
-
- const client = new MongoClient(uri);
- client.connect((err) => {
- const collection = client.db('test').collection('devices');
- // perform actions on the collection object
- client.close();
- });
- }
-
- main().catch(console.error);
'运行
还有另一种称为对象关系映射器 (ORM) 的方法 通过它我们可以间接访问数据库。这种方法以模型或对象的形式定义数据,ORM 使用底层数据库格式进行映射。
模板引擎用于生成固定类型的 HTML 结构和更多类型的文档,其中动态代码被放置在相应的占位符中。模板格式中的这些占位符是预定义的。Express js 也将模板引擎称为视图引擎。
nodejs express 支持的 Express 引擎有 - Pug、Mustache 和 EJS。要使用模板引擎,您需要为 express 定义两件事:
设置 nodejs express 应用程序以使用视图引擎:
- // requiring express, and path module
- const express = require("express");
- const path = require("path");
-
- // creating an express app using the express instance
- const app = express();
-
- // join the path where the express can look for the templates
- app.set("views", path.join(__dirname, "views"));
-
- // setting which views engine to use, in this case, 'template_engine_name'
- app.set("view engine", "template_engine_name");
要使用模板引擎,我们调用 reponse.render() 方法并使用 variable_name: Data to be passed format 将文件名与数据对象一起传递。
- app.get("/home", function (req, res) {
- res.render("index", { variable_name: “Data to be passed” });
- });
所有应用程序代码都可以存在于单个 javascript 文件中,但由于代码变得难以管理和阅读,因此不会出现任何场景。因此,我们可以说 express 不相信应用程序的文件夹结构,任何文件都可以放在任何目录中。
但是,我们通常遵循标准的 MVC 架构,即模型视图控制器结构。您还可以使用 Express Application Generator 创建模块化应用程序框架,该框架可以轻松扩展以创建 Web 应用程序。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。