当前位置:   article > 正文

其他内容:Node Js Express

其他内容:Node Js Express

概述

Nodejs 带有许多内置的核心模块和实用程序。这些可以帮助您创建应用程序,但这将是费力和困难的。因此,我们有一个很好的选择,那就是 Express js 框架,它建立在 http 核心模块之上,为我们提供了许多方便的功能和实用程序,使开发过程比以往任何时候都更简单、更快捷。

先决条件

您需要具备以下先决条件才能阅读本文:

  • Node js 和 npm 应该安装在系统本地。您可以从他们的官方网站下载 Node。
  • 对 javascript 函数、变量和语法有基本的了解,并了解 HTTP。

Express Framework 简介

Express js 框架体积小、开源、免费,于 2010 年发布。从技术上讲,express 是在 Node js 核心模块 http 的帮助下构建的,使开发周期更省时、更轻松。它本质上是用于 Node js 服务器(后端和 API 服务)开发的标准框架,目前版本为 4.0,版本 5.0 处于 beta 测试阶段。

Express 通过使用 Node.js 的核心模块,为您提供了一组实用程序,包括处理程序、路由器、控制器、中间件等。此外,对如何使用这些实用程序创建后端服务没有限制。因此,快速框架提供了有效启动开发过程所需的一切。

为什么使用 Express?

与其他后端服务相比,使用 Express 的一些优点是:

  • 简单易学:使用 Express 最明显的优势是它是用 Javascript 编写的。由于 javascript 是最著名的语言之一,并且广泛用于开发 Web 应用程序,因此适应 express 框架是值得的,并且很容易适应。
  • 后端和前端的语言相同:另一个好处是,将有一个堆栈(用 javascript 编写)将用于开发应用程序的前端和后端。虽然可以在不同的框架中编写前端和后端,但使用起来可能非常困难。
  • 可 伸缩:Express 允许您有效地扩展应用程序。众所周知,Node.js支持集群和进程与工作线程进行交互。我们可以使用一些额外的额外资源轻松扩展 Node js express 应用程序。
  • 社区:社区支持生态系统非常庞大。因此,如果您被困在某个地方,可以使用中间件(第三方库)形式的不同扩展来添加不同类型的功能,以便您可以完成工作。
  • 缓存:Express.js还支持服务器端缓存,从而提高了性能和效率。此外,此功能有助于更快地加载页面。

Nodejs 示例:

 
  1. // requiring the core http module
  2. const http = require('http');
  3. // creating server object
  4. const server = http.createServer((req, res) => {
  5. const url = req.url;
  6. // routing is not provided in nodejs hence checking for the URL of the request while sending the response
  7. if(url === '/') {
  8. res.write('<html>');
  9. res.write('<head><h1>Scaler Topics</h1><head>');
  10. res.write('<body><h2>Hello from Nodejs express framework example !!</h2></body>');
  11. res.write('</html>');
  12. return res.end();
  13. }
  14. // routing is not provided in nodejs hence checking for the URL of the requrest while sending the response
  15. if(url === '/about') {
  16. res.write('<html>');
  17. res.write('<head><h1>Scaler Topics</h1><head>');
  18. res.write('<body><h2>Nodesjs does not provide us with routing !!</h2></body>');
  19. res.write('</html>');
  20. return res.end();
  21. }
  22. });
  23. // setting up the server
  24. server.listen(3000, () => {
  25. console.log("Starting the server on port 3000")
  26. });

Nodejs Express 示例

 
  1. // requiring express module
  2. const express = require('express');
  3. // creating an app using express instance
  4. const app = express();
  5. // handling '/' request
  6. app.get('/', (req, res) => {
  7. res.send('<h1>Scaler Topics</h1>');
  8. });
  9. // handling '/about' request
  10. app.get('/about', (req,res) => {
  11. res.send('<h1>Hello from Nodejs Express framework example !!</h1>');
  12. });
  13. // setting up the server
  14. app.listen(8080, () => {
  15. console.log('Starting the server on port 3000');
  16. });
'
运行

安装 Express

现在,我们已经了解了 express 及其重要性,让我们开始使用 nodejs express。第一步是安装 express。按照以下步骤在您的系统中安装 express:

  1. 让我们创建一个目录,您将在其中启动您的Node.js express 项目。
 
mkdir express-app

现在导航到创建的目录:

 
cd express-app
  1. 导航到项目文件夹后,运行以下命令:
 
npm init

上述命令用于初始化Node.js项目。将提出有关该项目的一系列问题。之后,将创建一个包含有关项目信息的package.json文件。

  1. 现在使用 npm 安装 Express 包:
 
npm install express

上面的命令将安装 express。完成后将创建一个node_modules文件夹。package.json 文件将具有依赖项中提到的 express 及其版本。

示例:Helloworld Express

安装 express 后,让我们创建一个小型 express 应用程序。 在项目目录下创建一个server.js文件,并在其中编写以下代码:

 
  1. // require express module
  2. const express = require('express')
  3. // creating an app using express instance
  4. const app = express()
  5. // Setting app PORT as 8080.
  6. const PORT = 8080
  7. // Create a get endpoint at baseURL.
  8. app.get('/', (req, res) => {
  9. res.send('Hello World!!')
  10. })
  11. // Make the app listen on the specified port
  12. app.listen(PORT, () => {
  13. console.log(`Express app listening on port ${PORT}`)
  14. })

现在保存文件并执行以下命令以运行代码:

 
node server.js

当应用程序启动时,您将在终端中收到以下消息:

 
Express app listening on port 8080

现在在 Web 浏览器中打开 localhost:8080,您将看到以下输出:

导入和创建模块

模块是一段封装的代码,我们可以将其导入到项目其他部分的任何位置。可以在 require() 函数的帮助下导入模块。

语法如下所示

 
const moduleName = require(‘module-name’)

Express 是第三方模块

 
  1. const express = require("express");
  2. const app = express();

首先,我们必须导入模块,然后调用返回的对象来创建快速应用程序。

我们同样可以导入其他模块:

 
  1. var mongoose = require("mongoose");
  2. var fs = require("fs");

我们还可以创建模块并以类似的方式导入它们。要导出函数或变量,我们必须使用 exports 对象。exports 对象是对 module.exports 的引用,其中 module 是全局的。语法如下:

 
  1. exports.<module_name / variable_name / function_name > = <module_name / variable_name / function_name >`

让我们创建一个文件util.js并在文件中导出一组函数:

 
  1. function createUser(userInfo){
  2. validate(userInfo)
  3. //connect to db and process user registration.
  4. }
  5. function validate(userInfo){
  6. // Code for validating user info and returning errors if any
  7. }
  8. function login(userCredentials){
  9. // Code for validating user info and
  10. //Handling user login if credentials are right
  11. }
  12. exports.createUser = createUser
  13. exports.validate = validate
  14. exports.login = login
'
运行

我们现在可以将函数导入到任何其他文件中,如下所示:

 
  1. // If util.js and the current file are in the same directory.
  2. const { createUser, validate, login } = require("./util")

现在,所有这些函数都可以在当前文件中使用。

请求和响应

express Request 对象表示 HTTP 请求,并具有查询字符串、正文、标头等属性。响应对象表示 HTTP 响应。它用于将响应发送回浏览器或在客户端的浏览器中添加 cookie 值。

例:

 
  1. var express = require("express");
  2. var app = express();
  3. var PORT = 8080;
  4. bodyParser = require("body-parser");
  5. // support parsing of application/json type post data
  6. const urlEncParser = bodyParser.urlencoded({ extended: true });
  7. // Use of middleware to parse the body of the request in JSON form.
  8. app.post("/form", urlEncParser, (req, res) => {
  9. // Print the body of request
  10. console.log("Body : ", req.body);
  11. // Print the Headers of request
  12. console.log("Headers : ", req.headers);
  13. // Print the Query String of request
  14. console.log("Query String : ", req.query);
  15. // Print the path of request
  16. console.log("Path : ", req.path);
  17. // Print the cookie data sent with request
  18. console.log("Cookies : ", req.cookies);
  19. // Get the firstname and lastname from the body of the request and combine them and send them as fullname
  20. const data = {
  21. fullname: req.body.firstname + " " + req.body.lastname,
  22. };
  23. // Add cookie info in the user's browser.
  24. res.cookie("Info", { SampleKey: "Sample data" });
  25. // Send the response using res.send() method.
  26. res.send(JSON.stringify(data));
  27. });
  28. app.listen(PORT, function (err) {
  29. if (err) console.log(err);
  30. console.log(`Server listening on PORT: ${PORT}`);
  31. });

输出:

 
  1. Server listening on PORT: 8080
  2. Body: { firstname: 'John', lastname: 'Doe' }
  3. Headers: {
  4. host: '127.0.0.1:8080',
  5. connection: 'keep-alive',
  6. 'content-length': '27',
  7. 'cache-control': 'max-age=0',
  8. ...
  9. origin: 'null',
  10. 'content-type': 'application/x-www-form-urlencoded',
  11. ...
  12. cookie: undefined,
  13. 'if-none-match': 'W/"17-1+uiygXxvKCInIP4KZEKUIq9o6Q"'
  14. }
  15. Query String: {}
  16. Path: /form
  17. Cookies: undefined

基本路由

路由定义了应用程序如何响应特定路径(或 URI)上的 HTTP 请求方法(GET、POST 等)。每个路由都与一个或多个处理程序函数相关联。处理程序函数用于定义该路由的逻辑。

路由的定义可以概括如下:

 
app.METHOD( route_path, handler_function )

以上代码说明:

  • app - Express 实例。
  • METHOD - HTTP 请求方法。
  • Route_path - 服务器上的路径。
  • Handler_function - 与给定路由选项关联的函数。

让我们看一些例子:

  • 位于 / 路由的 GET 请求的终结点。

     
      
    1. app.get('/', ( req, res ) => {
    2. res.send(' Get request at / path ')
    3. })
  • /user 路由中 POST 请求的终结点。

     
      
    1. app.post('/user', ( req, res ) => {
    2. res.send(' POST request at /user ')
    3. })
  • /user 路由中 PUT 请求的终结点。

     
      
    1. app.put('/user', ( req, res ) => {
    2. res.send(' PUT request at /user ')
    3. })
  • /user 路由中 DELETE 请求的终结点。

     
      
    1. app.delete('/user', ( req, res ) => {
    2. res.send(' DELETE request at /user ')
    3. })

使用异步 API

在同步操作中,主线程的执行将被阻止,直到操作完成。仅当电流完成时,下一个操作才会开始。

 
  1. console.log(" Statement 1 ");
  2. console.log(" Statement 2 ");

例如,在上面的代码中,第一个 console.log() 将执行,之后第二个将执行。

在异步 API 中,操作放置在事件队列中,并且主线程不会被阻塞。这样,就可以处理异步 API。这加快了应用程序的速度,也提高了效率。如果我们将第一个 console.log() 放在 setTimeout() 函数中,输出将被反转:

 
  1. setTimeout( () =>
  2. console.log(" Statement 1 "),
  3. 1000);
  4. console.log("Statement 2");

输出:

 
  1. Statement 2
  2. Statement 1

我们可以使用 async await 或 promise 来处理异步操作。让我们看一下使用 promise 处理异步代码的处理函数。

 
  1. app.get('/', function( req, res ) {
  2. // query some data from the database
  3. queryDB()
  4. .then(function (data) {
  5. // handle data
  6. return OperationA(data)
  7. })
  8. .then(function (res) {
  9. // handle res
  10. })
  11. })

在上面的代码片段中,假设 queryDB() 是一个使用从数据库查询数据的函数,完成此操作后,将调用 .then 处理程序并接收 queryDB() 的输出。这在承诺链上进一步延伸。

完成上述操作的另一种方法是使用 async-await,我们可以使函数异步并使用 await 完成 promise。

让我们来看看。

 
  1. app.get('/',async function (req, res) {
  2. // query some data from the database
  3. const data = await queryDB()
  4. const res = await OperationA(data)
  5. // handle res
  6. });

提供静态文件

静态文件(如图像、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(下一个中间件函数)。

 
  1. app.use(function (err, req, res, next) {
  2. console.error( err );
  3. res.status(500).send(" Server Error !!! ");
  4. });

这个中间件应该在所有路由和其他中间件之后使用,这样如果没有中间件可以处理请求,那么错误就会被处理。

Express 还具有内置的错误处理程序。如果所描述的中间件都无法处理错误,则 express 内置处理程序会将错误消息发送给带有堆栈跟踪的 fluent。

GET 方法

HTTP Get 方法用于从服务器获取资源。它可以将有限数量的数据作为 URL 参数传递。让我们在 express 的帮助下使用 GET 方法。

在server.js文件中,编写以下代码:

 
  1. // requiring express and creating an app using express instance
  2. var express = require("express");
  3. var app = express();
  4. var PORT = 8080;
  5. app.get("/form", ( req, res ) => {
  6. // Get the firstname and lastname as query parameters and combine them and send them as fullname
  7. const data = {
  8. fullname: req.query.firstname + " " + req.query.lastname,
  9. };
  10. console.log(data);
  11. // Send response
  12. res.send(JSON.stringify(data));
  13. });
  14. app.listen(PORT, function (err) {
  15. if (err) {
  16. console.log(err);
  17. }
  18. console.log(` Server listening on PORT: ${PORT} `);
  19. });

创建一个文件form.html以制作一个小表单,如下所示:

 
  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <form action="http://127.0.0.1:8080/form" method="GET">
  5. Write your First Name: <input type="text" name="firstname" />
  6. <br />
  7. Write your Last Name: <input type="text" name="lastname" />
  8. <input type="submit" value="Submit" />
  9. </form>
  10. </body>
  11. </html>

form.html的输出如下所示:

按提交后,网页将显示以下响应:

服务器控制台将显示以下内容:

 
  1. $ node server.js
  2. Server listening on PORT 8080
  3. { fullname : 'John Doe'}

在上面的代码中,firstname 和 lastname 作为查询参数传递,请求由 get 端点处理。处理程序函数以全名形式提供响应。

POST 方法

POST 方法用于在请求正文中发送大量数据。数据也是安全的,因为它在 URL 中不可见。

现在让我们在 POST 的帮助下实现相同的示例。

在server.js文件中编写以下代码。

 
  1. // requiring express and creating an app using express instance
  2. var express = require("express");
  3. var app = express();
  4. var PORT = 8080;
  5. // requiring body-parser
  6. bodyParser = require("body-parser");
  7. // support parsing of application/json type post data
  8. const urlEncParser = bodyParser.urlencoded({ extended: true });
  9. // Use of middleware to parse the body of the request in JSON form.
  10. app.post("/form", urlEncParser, (req, res) => {
  11. console.log(req.body);
  12. // Get the firstname and lastname from the body of the request and combine them and send them as fullname
  13. const data = {
  14. fullname: req.body.firstname + " " + req.body.lastname,
  15. };
  16. console.log(data);
  17. res.send(JSON.stringify(data));
  18. });
  19. app.listen(PORT, function (err) {
  20. if (err) {
  21. console.log(err);
  22. }
  23. console.log(`Server listening on PORT: ${PORT}`);
  24. });

在form.html中进行更改,如下所示:

 
  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <form action="http://127.0.0.1:8080/form" method="POST">
  5. Write your First Name: <input type="text" name="firstname" />
  6. <br />
  7. Write your Last Name: <input type="text" name="lastname" />
  8. <input type="submit" value="Submit" />
  9. </form>
  10. </body>
  11. </html>

上面的代码将提供与 GET 类似的输出,只是数据在 URL 中不可见。

文件上传

让我们看看如何使用 POST 方法上传文件。index.html代码如下:

 
  1. <html>
  2. <head>
  3. <title>File Uploading Tutorial</title>
  4. </head>
  5. <body>
  6. <h1>File Upload:</h1>
  7. Select the file to upload:
  8. <br />
  9. <form action = "http://127.0.0.1:8081/file_upload" method = "POST"
  10. enctype = "multipart/form-data">
  11. <input name="file" type="file" size="100" />
  12. <br />
  13. <input type = "submit" value = "Upload File" />
  14. </form>
  15. </body>
  16. </html>

现在,让我们修改server.js以处理表单数据:

 
  1. // requiring the necessary modules
  2. var express = require('express');
  3. var app = express();
  4. var fs = require("fs");
  5. // body-parser will handle the JSON data
  6. var bodyParser = require('body-parser');
  7. var multer = require('multer');
  8. // including all the middlewares
  9. app.use(express.static('public'));
  10. app.use(bodyParser.urlencoded({ extended: false }));
  11. // specifing the destination folder of the files
  12. app.use(multer({ dest: '/tmp/'}));
  13. app.get('/index.htm', function (req, res) {
  14. res.sendFile( __dirname + "/" + "index.htm" );
  15. })
  16. // handling the POST request at /file_upload
  17. app.post('/file_upload', function (req, res) {
  18. var file = __dirname + "/" + req.files.file.name;
  19. fs.readFile( req.files.file.path, function (err, data) {
  20. fs.writeFile(file, data, function (err) {
  21. if( err ) {
  22. console.log( err );
  23. } else {
  24. response = {
  25. message:'File successfully uploaded',
  26. filename:req.files.file.name
  27. };
  28. }
  29. res.end( JSON.stringify( response ) );
  30. });
  31. });
  32. })
  33. var server = app.listen(8080, function (err) {
  34. if (err) {
  35. console.log(err);
  36. }
  37. console.log(`Server listening on PORT: ${PORT}`);
  38. })

现在您可以检查表格

http://127.0.0.1:8080/index.htm。

Cookies管理

当用户浏览该网站时,存储在用户浏览器中的一小段数据称为 cookie。每次用户重新加载网站时,此数据都会发送回服务器,以区分用户以前的活动。我们使用 cookie-parser 包在 nodejs express 应用程序中使用 cookie。通过使用此软件包,我们可以顺利地管理cookie。

安装cookie管理包:

 
npm install cookie-parser

cookie-parser 的语法:

 
  1. app.get('/set_cookie_route', function( req, res ) {
  2. res.cookie(cookie_name , 'cookie_value').send('Cookie is set');
  3. });

在 nodejs express 应用程序中添加此中间件:

 
  1. // requiring the express and cookie-parser module
  2. const express = require('express');
  3. const cookieParser = require('cookie-parser');
  4. const app = express();
  5. // adding cookieParser to the middleware stack
  6. app.use(cookieParser());

上面的模块放弃了对 req.cookies 的访问,其中包含一个具有 cookie 名称及其属性的对象。

我们还可以使用 req.secret 通过传递密钥字符串来启用签名的支持 cookie。

设置 Cookie:

 
  1. app.get('/cookie_route', function(req, res) {
  2. // setting maxAge of cookie
  3. const time = 55 * 1000;
  4. res.cookie(cookie_name, 'cookie_value', { maxAge : minute });
  5. return res.send('Cookie has been set !!!');
  6. });

上面代码中使用的 maxAge 选项是可选的。让我们看看其他选项:

  • 要设置过期时间(以毫秒为单位):
     
      
    res.cookie(cookie_name, 'cookie_value', {expire : 24 * 60 * 60 * 1000 });
    
  • 要仅在 HttpOnly 上设置 cookie:
     
      
    res.cookie(cookie_name, 'cookie_value', { HttpOnly : true});
    
  • 要使用加密的 http 通道进行安全的 cookie 数据交换:
     
      
    res.cookie(cookie_name, 'cookie_value',  { secure : true});
    

阅读 Cookie:

用户可以使用以下命令访问 cookie:req.cookies 或 req.cookies.cookie_name。

删除 Cookie:

我们可以简单地使用浏览器开发人员工具删除 cookie,也可以简单地使用 res.clearCookie() 方法。此函数接受单个参数,即要删除的 cookie 的名称。

 
  1. app.get('/delete_cookie_route', function(req, res) {
  2. res.clearCookie('cookie_name');
  3. res.send('Cookie is deleted');
  4. });
'
运行

使用数据库

Nodejs Express 应用程序支持许多数据库服务,如 MongoDB、SQL、SQLite、PostgreSQL、Redis 等。Express 本身不会为数据库管理服务定义任何额外的特定条件或行为。数据库服务可以是基于云的,也可以存在于系统中的本地。若要使用上述服务提供商,需要安装其驱动程序,然后将应用与该数据库服务连接。

让我们以 MongoDB 连接为例。 安装MongoDB驱动程序:

 
npm install mongodb --save

现在让我们将数据库连接到您的 Nodejs express 应用程序:

 
  1. async function main() {
  2. const MongoClient = require('mongodb').MongoClient;
  3. const uri = 'mongodb+srv://dbUser:<dbpassword>@cluster0.dcu5m.mongodb.net/sample_airbnb?retryWrites=true&w=majority';
  4. const client = new MongoClient(uri);
  5. client.connect((err) => {
  6. const collection = client.db('test').collection('devices');
  7. // perform actions on the collection object
  8. client.close();
  9. });
  10. }
  11. main().catch(console.error);
'
运行

还有另一种称为对象关系映射器 (ORM) 的方法 通过它我们可以间接访问数据库。这种方法以模型或对象的形式定义数据,ORM 使用底层数据库格式进行映射。

呈现数据(视图)

模板引擎用于生成固定类型的 HTML 结构和更多类型的文档,其中动态代码被放置在相应的占位符中。模板格式中的这些占位符是预定义的。Express js 也将模板引擎称为视图引擎。

nodejs express 支持的 Express 引擎有 - Pug、Mustache 和 EJS。要使用模板引擎,您需要为 express 定义两件事:

  • 您将使用哪个模板引擎名称,以及
  • express可以在什么位置找到要渲染的模板或视图?

设置 nodejs express 应用程序以使用视图引擎:

 
  1. // requiring express, and path module
  2. const express = require("express");
  3. const path = require("path");
  4. // creating an express app using the express instance
  5. const app = express();
  6. // join the path where the express can look for the templates
  7. app.set("views", path.join(__dirname, "views"));
  8. // setting which views engine to use, in this case, 'template_engine_name'
  9. app.set("view engine", "template_engine_name");

要使用模板引擎,我们调用 reponse.render() 方法并使用 variable_name: Data to be passed format 将文件名与数据对象一起传递。

 
  1. app.get("/home", function (req, res) {
  2. res.render("index", { variable_name: “Data to be passed” });
  3. });

文件结构

所有应用程序代码都可以存在于单个 javascript 文件中,但由于代码变得难以管理和阅读,因此不会出现任何场景。因此,我们可以说 express 不相信应用程序的文件夹结构,任何文件都可以放在任何目录中。

但是,我们通常遵循标准的 MVC 架构,即模型视图控制器结构。您还可以使用 Express Application Generator 创建模块化应用程序框架,该框架可以轻松扩展以创建 Web 应用程序。

结论

  • Express 是开源的,是一个用于Node.js的快速 Web 框架。
  • Express 以处理程序、路由器、控制器和中间件的形式为您提供了一组实用程序。
  • 路由定义了应用程序如何响应 HTTP 请求方法(GET、POST 等)。
  • GET 方法用于获取数据,而 POST 方法用于向服务器发送数据。
  • Express 服务器使用中间件的静态文件 express.static() 也有一个内置的错误处理程序。
  • 我们使用 async await 或 promise 来处理 nodejs express 中的异步操作。
  • cookie-parser 包用于 NodeJS Express 应用程序中的 cookie 处理。
  • Nodejs express 支持许多数据库服务,如 MongoDB、SQL 和模板引擎,如 pug、ejs 等。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/986838
推荐阅读
相关标签
  

闽ICP备14008679号