expressjs mp4

With the new ExpressJS 4.0 just being released last week, there are many changes that have come with it. These changes will affect how we build Node and MEAN stack apps in the future.

随着上周刚刚发布的新ExpressJS 4.0,已经有了许多变化。 这些变化将影响我们将来构建Node和MEAN堆栈应用程序的方式。

Since Express has a such a large presence in our Node applications, let's take a look at how we can use the new features in our applications, specifically the Router.

由于Express在我们的Node应用程序中占有如此庞大的席位,因此让我们看一下如何在应用程序中使用新功能,特别是在路由器中。

总览 (Overview)

Express 4.0 comes with the new Router. Router is like a mini express application. It doesn't bring in views or settings, but provides us with the routing APIs like .use, .get, .param, and route.

Express 4.0随附了新的Router 。 路由器就像一个小型快递应用程序。 它没有引入视图或设置,但为我们提供了诸如.use.get.paramroute的路由API。

Let's look at how many of us route our applications and let's see how we can recreate that with Router.

让我们看看有多少人路由应用程序,并看看如何使用Router重新创建它。

我们的样品申请 (Our Sample Application)

Let's create an application that has some routes and a few features. Let's run through those now.

让我们创建一个具有一些路由和一些功能的应用程序。 让我们现在来看这些。

  • Basic Routes: Home, About基本路线 :首页,关于
  • Route Middleware to log requests to the console路由中间件以将请求记录到控制台
  • Route with Parameters带参数的路线
  • Route Middleware for Parameters to validate specific parameters路由参数中间件以验证特定参数
  • Login routes Doing a GET and POST on /login登录路线在/ login上执行GET和POST
  • Validates a parameter passed to a certain route验证传递给特定路由的参数

应用结构 (Application Structure)

We'll only need two files for our application.

我们的应用程序只需要两个文件。

- package.json  // set up our node packages
- server.js     // set up our app and build routes

We will house our routes in the server.js file. In the future we'll want to move these out into their own files to keep our application modular. We can even define different route files for different sections of our site.

我们将路由保存在server.js文件中。 将来,我们将希望将它们移到它们自己的文件中,以保持我们的应用程序模块化。 我们甚至可以为站点的不同部分定义不同的路由文件。

开始我们的申请 (Starting Our Application)

Let's start up our Node application. We will need our package.json file to define our dependencies.

让我们启动Node应用程序。 我们将需要package.json文件来定义依赖项。

{"name": "express-router-experiments","main": "server.js","dependencies": {"express": "~4.0.0"}
}

We'll only need one dependency, Express! Pretty sweet to see that 4.0.0 after seeing 3.x.x for so long.

我们只需要一个依赖,Express! 看到3.xx这么长时间后,很高兴看到4.0.0。

@media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }} @media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }}

Go ahead and install our dependencies.

继续安装我们的依赖项。

$ npm install

Now we have Express. Let's look at starting up our application and then we can handle our routing.

现在我们有快递。 让我们来看一下启动应用程序,然后我们可以处理路由。

创建我们的服务器 (Creating Our Server)

We will use Express to start our application server. Since we defined server.js as the main file in package.json, that is the file that Node will use. Let's define that file now.

我们将使用Express启动我们的应用程序服务器。 由于我们在package.json中将server.js定义为主文件,因此Node将使用该文件。 现在定义该文件。

// server.js// BASE SETUP
// ==============================================var express = require('express');
var app     = express();
var port    =   process.env.PORT || 8080;// ROUTES
// ==============================================// sample route with a route the way we're used to seeing it
app.get('/sample', function(req, res) {res.send('this is a sample!');
});// we'll create our routes here// START THE SERVER
// ==============================================
app.listen(port);
console.log('Magic happens on port ' + port);

Now we can start our server. We've created a route using the normal app.get that we've used in our Express 3.0 applications. If we go into our browser and visit http://localhost:8080/sample, we will be able to see this is a sample!. Now we'll move to creating routes using the Express 4.0 Router.

现在我们可以启动服务器了。 我们使用Express 3.0应用程序中使用的常规app.get创建了一条路由。 如果进入浏览器并访问http://localhost:8080/sample ,我们将能够看到这是一个示例! 。 现在,我们将开始使用Express 4.0 Router创建路由。

快速路由器 (Express Router)

What exactly is the Express Router? It is a mini express application without all the bells and whistles of an express application, just the routing stuff. Let's take a look at exactly what this means. We'll go through each section of our site and use different features of the Router.

Express Router到底是什么? 这是一个小型快递应用程序,没有快递应用程序的所有花哨功能,只是路由的东西。 让我们看看这到底意味着什么。 我们将遍历站点的每个部分,并使用路由器的不同功能。

基本路线express.Router() (Basic Routes express.Router())

Let's call an instance of the Router for creating our frontend routes for our application. This will include the Home and About pages.

让我们调用Router的一个实例,为我们的应用程序创建前端路由。 这将包括“ 主页”和“ 关于”页面。

// server.js...// we'll create our routes here// get an instance of router
var router = express.Router();// home page route (http://localhost:8080)
router.get('/', function(req, res) {res.send('im the home page!');
});// about page route (http://localhost:8080/about)
router.get('/about', function(req, res) {res.send('im the about page!');
});// apply the routes to our application
app.use('/', router);...

We will call an instance of the express.Router(), apply routes to it, and then tell our application to use those routes. We can now access the home page at http://localhost:8080 and the about page at http://localhost:8080/about.

我们将调用express.Router()的实例,对其应用路由,然后告诉我们的应用程序使用这些路由。 现在,我们可以在http:// localhost:8080访问主页,并在http:// localhost:8080 / about访问about页面。

Notice how we can set a default root for using these routes we just defined. If we had changed line 21 to app.use('/app', router), then our routes would be http://localhost:8080/app and http://localhost:8080/app/about.

注意,我们如何为使用刚定义的这些路由设置默认根。 如果我们将第21行更改为app.use('/app', router) ,那么我们的路由将为http:// localhost:8080 / apphttp:// localhost:8080 / app / about

This is very powerful because we can create multiple express.Router()s and then apply them to our application. We could have a Router for our basic routes, authenticated routes, and even API routes.

这非常强大,因为我们可以创建多个express.Router() ,然后将它们应用于我们的应用程序。 我们可以为基本路由,经过身份验证的路由甚至API路由设置一个路由器。

Using the Router, we are allowed to make our applications more modular and flexible than ever before by creating multiple instances of the Router and applying them accordingly. Now we'll take a look at how we can use middleware to handle requests.

通过使用路由器,我们可以通过创建路由器的多个实例并相应地应用它们,使我们的应用程序比以往更加模块化和灵活。 现在,我们来看看如何使用中间件来处理请求。

路由中间件router.use() (Route Middleware router.use())

Route middleware in Express is a way to do something before a request is processed. This could be things like checking if a user is authenticated, logging data for analytics, or anything else we'd like to do before we actually spit out information to our user.

Express中的路由中间件是一种在处理请求之前执行某些操作的方法。 这可能是诸如检查用户是否通过身份验证,记录数据以进行分析或在实际向用户吐出信息之前我们想做的其他事情。

Here is some middleware to log a message to our console every time a request is made. This will be a demonstration of how to create middleware using the Express Router.

这是一些中间件,用于在每次发出请求时将消息记录到控制台。 这将演示如何使用Express Router创建中间件。

// server.js...// we'll create our routes here// get an instance of router
var router = express.Router();// route middleware that will happen on every request
router.use(function(req, res, next) {// log each request to the consoleconsole.log(req.method, req.url);// continue doing what we were doing and go to the routenext();
});// home page route (http://localhost:8080)
router.get('/', function(req, res) {res.send('im the home page!');
});// about page route (http://localhost:8080/about)
router.get('/about', function(req, res) {res.send('im the about page!');
});// apply the routes to our application
app.use('/', router);...

We'll use router.use() to define middleware. This will now be applied to all of the requests that come into our application for this instance of Router. Let's go into our browser and go to http://localhost:8080 and we'll see the request in our console.

我们将使用router.use()定义中间件。 现在,这将应用于该路由器实例的所有进入我们应用程序的请求。 让我们进入浏览器并转到http:// localhost:8080 ,我们将在控制台中看到该请求。

The order you place your middleware and routes is very important. Everything will happen in the order that they appear. This means that if you place your middleware after a route, then the route will happen before the middleware and the request will end there. Your middleware will not run at that point.

放置中间件和路由的顺序非常重要 。 一切都会按照它们出现的顺序进行。 这意味着,如果将中间件放置在路由之后,则路由将发生在中间件之前,并且请求将在此处结束。 那时您的中间件将无法运行。

Keep in mind that you can use route middleware for many things. You can use it to check that a user is logged in in the session before letting them continue.

请记住,您可以将路由中间件用于许多事情。 您可以使用它来检查用户是否在会话中登录,然后再继续。

使用参数/ hello /:name进行路由 (Route with Parameters /hello/:name)

Let's say we wanted to have a route called /hello/:name where we could pass in a person's name into the URL and the application would spit out Hello *name*!. Let's create that route now.

假设我们想要一个名为/hello/:name的路由,可以在其中将一个人的名字传递到URL中,应用程序将吐出Hello * name *! 。 现在创建该路线。

// server.js...// we'll create our routes here// get an instance of router
var router = express.Router();...// route with parameters (http://localhost:8080/hello/:name)
router.get('/hello/:name', function(req, res) {res.send('hello ' + req.params.name + '!');
});// apply the routes to our application
app.use('/', router);...

Now we can visit http://localhost:8080/hello/holly and see our browser spit out hello holly! Easy cheese.

现在我们可以访问http://localhost:8080/hello/holly并看到我们的浏览器吐出你好霍莉! 简单的奶酪。

Now let's say we wanted to validate this name somehow. Maybe we'd want to make sure it wasn't a curse word. We would do that validation inside of route middleware. We'll use a special middleware for this.

现在,我们要以某种方式验证此名称。 也许我们想确保它不是一个诅咒词。 我们将在路由中间件内部进行验证。 为此,我们将使用特殊的中间件。

路由中间件获取参数 (Route Middleware for Parameters)

We will use Express's .param() middleware. This creates middleware that will run for a certain route parameter. In our case, we are using :name in our hello route. Here's the param middleware.

我们将使用Express的.param()中间件。 这将创建将针对特定路由参数运行的中间件。 在我们的例子中,我们在问候路由中使用:name 。 这是参数中间件。

// server.js...// we'll create our routes here// get an instance of router
var router = express.Router();...// route middleware to validate :name
router.param('name', function(req, res, next, name) {// do validation on name here// blah blah validation// log something so we know its workingconsole.log('doing name validations on ' + name);// once validation is done save the new item in the reqreq.name = name;// go to the next thingnext();
});// route with parameters (http://localhost:8080/hello/:name)
router.get('/hello/:name', function(req, res) {res.send('hello ' + req.name + '!');
});// apply the routes to our application
app.use('/', router);...

Now when we hit the /hello/:name route, our route middleware will kick in and be used. We can run validations and then we'll pass the new variable to our .get route by storing it in req. We then access it by changing req.params.name to req.name.

现在,当我们点击/ hello /:name路由时,我们的路由中间件将启动并被使用。 我们可以运行验证,然后将新变量存储在req以将新变量传递到.get路由。 然后,我们通过改变req.params.namereq.name访问它。

When we visit our browser at http://localhost:8080/hello/sally we'll see our request logged to the console.

当我们通过http:// localhost:8080 / hello / sally访问浏览器时,我们将看到请求记录到控制台。

Route middleware for parameters can be used to validate data coming to your application. If you have created a RESTful API also, you can validate a token and make sure the user is able to access your information.

用于参数的路由中间件可用于验证进入您的应用程序的数据。 如果您还创建了RESTful API,则可以验证令牌并确保用户能够访问您的信息。

The last thing we'll look at today is how to use app.route() to define multiple routes.

我们今天要看的最后一件事是如何使用app.route()定义多个路由。

登录路线app.route (Login Routes app.route)

We can define our routes right on our app. This is similar to using app.get, but we will use app.route. app.route is basically a shortcut to call the Express Router. Instead of calling express.Router(), we can call app.route and start applying our routes there.

我们可以在我们的app上定义路线。 这类似于使用app.get ,但是我们将使用app.route 。 app.route基本上是调用Express Router的快捷方式。 除了调用express.Router() ,我们还可以调用app.route并在那里开始应用路由。

Using app.route lets us define multiple actions on a single login route. We'll need a GET route to show the login form and a POST route to process the login form.

使用app.route,我们可以在一个登录路径上定义多个操作。 我们将需要一个GET路由来显示登录表单,并需要一个POST路由来处理登录表单。

...// ROUTES
// ==============================================app.route('/login')// show the form (GET http://localhost:8080/login).get(function(req, res) {res.send('this is the login form');})// process the form (POST http://localhost:8080/login).post(function(req, res) {console.log('processing');res.send('processing the login form!');});...

Now we have defined our two different actions on our /login route. Simple and very clean.

现在,我们在/login路由上定义了两个不同的动作。 简单而且很干净。

结论 (Conclusion)

With the inclusion of the Express 4.0 Router, we are given more flexibility than ever before in defining our routes. To recap, we can:

通过包含Express 4.0路由器,我们在定义路由时比以往有了更大的灵活性。 回顾一下,我们可以:

  • Use express.Router() multiple times to define groups of routes多次使用express.Router()定义路由组
  • Apply the express.Router() to a section of our site using app.use()使用app.use()将express.Router()应用于我们网站的app.use()
  • Use route middleware to process requests使用路由中间件处理请求
  • Use route middleware to validate parameters using .param()使用路由中间件通过.param()验证参数
  • Use app.route() as a shortcut to the Router to define multiple requests on a route使用app.route()作为路由器的快捷方式来定义路由上的多个请求

With all the ways we can define routes, I'm sure that our applications will benefit going forward. Sound off in the comments if you have any questions or suggestions.

通过所有可以定义路由的方法,我相信我们的应用程序将继续向前发展。 如果您有任何疑问或建议,请在评论中取消提示。

翻译自: https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4

expressjs mp4

expressjs mp4_了解如何在ExpressJS 4.0中使用新路由器相关推荐

  1. 如何在 vue-cli v3.0 中使用 SCSS/SASS

    在项目中使用 SCSS/SASS 进行样式编写无疑会节省很多开发样式的时间.关于如何在 vue-cli v3.0 中使用 SCSS/SASS,这里提供三种方案.前提是在使用 vue-cli 生成项目时 ...

  2. 如何在Axure 9.0 中使用echarts

    如何在Axure 9.0 中使用echarts 在需要插入echarts的页面中交互事件 -> 页面载入时 -> 打开链接 ,加入如下代码,插入echats代码. javascript: ...

  3. ubuntu添加路由_如何在Ubuntu,Linux中添加新路由?

    ubuntu添加路由 I have a box with Ubuntu Linux and I want to add a new route to my box. Because I want to ...

  4. asp.net 2.0中,新增加了validationgroup属性

    asp.net 1.1中,对于验证类控件,在使用时,遇到有的不需要验证的控件时,是十分麻烦的,就是说不可能有选择验证某些控件. 而在asp.net 2.0中,新增加了validationgroup属性 ...

  5. 在Redhat9.0中安装新ATI显卡

    在Redhat9.0中安装新ATI显卡(9200) 因为RH9支持老机器中绝大部分硬件(除了S90),所以就没机会练习如果配置XFREE86等和硬件有关的技术.这回换新机器了问题也就来了,今天先说说显 ...

  6. pythonfillcolor填充不了颜色_如何在matplotlib 2.0中仅使用图案填充(无背景色)填充区域...

    matplotlib&gt:2.0.1 由于GitHub上有很多关于填充的discussion,现在引入了一些更改,使填充更加直观. 如果使用的是facecolor参数而不是color参数,则 ...

  7. buddypress主题_如何在WordPress 3.0中启用BuddyPress

    buddypress主题 In WPMU, there was an option that would let you add Buddypress function on all multi-bl ...

  8. .NET Core 3.0 中的新变化

    译者:楚人Leo 译文:http://www.cnblogs.com/leolion/p/10585834.html 原文:https://msdn.microsoft.com/en-us/magaz ...

  9. 在.Net Core 3.0中尝试新的System.Text.Json API

    .NET Core 3.0提供了一个名为System.Text.Json的全新命名空间,它支持reader/writer,文档对象模型(DOM)和序列化程序.在此博客文章中,我将介绍它如何工作以及如何 ...

最新文章

  1. C++:文件操作2 文本文件和二进制文件的读写
  2. 全球及中国太阳能光热发电市场重点项目规划及发展格局展望报告2021-2027年
  3. php mvc cms企业站,Phpcms V9程序目录结构及MVC简析
  4. 计算机专业相关的毕业设计论文合集免费下载
  5. Linux进程间通信之管道(pipe)、命名管道(FIFO)与信号(Signal)
  6. 转JMeter 利用Jmeter批量数据库插入数据
  7. 第十九章 TCP的交互数据流
  8. matlab 支撑集,基于OMP算法的快速压缩感知图像重构
  9. spring源码下载以及gradle的详细使用教程
  10. “一键淘宝”将淘宝网店免费转移到手机客户端教程
  11. 给Jetson Nano更换eMMC闪存(扩容)
  12. pyspark案例系列11-ALS推荐算法
  13. 苹果手机换品胜电池后还能保持峰值状态吗?
  14. 万能地图下载器矢量标注功能特性
  15. AI算法工程师必知必会的mysql语法
  16. 针对Windows10下EPLAN2.7频繁重启的解决办法
  17. 转:详尽的变速器调节方法
  18. Win10常用快捷键总结
  19. android 离线语言识别
  20. 自定义java对象转换工具类

热门文章

  1. 三星910S3L单m2接口更换硬盘系统克隆全程攻略
  2. 计算机网络故障的一般识别与解决方法 论文,计算机网络常见故障的一般识别与解决方法-职业学院毕业论文.doc...
  3. 明日之后无限信用点的服务器,明日之后免费刷信用点特别版
  4. html5 连接wifi,aWiFi是什么?
  5. 使用Visio画UML模型
  6. 哪个软件能代替斐讯路由_斐讯路由器控制软件 4.2.1 去广告版 - 用手机管理斐讯路由器...
  7. 写一个块设备驱动程序
  8. 用数字万用表精确测量小电阻
  9. NAACL 2022 | 具有元重加权的鲁棒自增强命名实体识别技术
  10. QString自动补全