by Pau Pavón

通过保罗·帕文(PauPavón)

使用Express在Node.js中实现非常基本的路由 (Really, really basic routing in Node.js with Express)

The goal of this story is to briefly explain how routing works in Express while building a simple — very simple — Node app.

这个故事的目的是简要解释路由在Express中的工作原理,同时构建一个简单的Node应用程序。

We’ll also use EJS, a template engine that “lets you generate HTML markup with plain JavaScript,” according to their website. Basically, it’ll let us create HTML pages that can vary depending on the request the client makes. We won’t be using this last feature, but it’s a great one. At the end of this article, you’ll find some resources where you can learn more.

根据他们的网站 ,我们还将使用EJS,这是一个模板引擎,“可以让您使用纯JavaScript生成HTML标记”。 基本上,它使我们可以创建HTML页面,该页面可以根据客户端的请求而有所不同。 我们不会使用最后一项功能,但这是一个很棒的功能。 在本文的结尾,您将找到一些资源,可以在其中了解更多信息。

什么是路由? (以两行表示) (What is routing? (In 2-ish lines))

First of all, let’s take a quick (really quick) glance at what routing is:

首先,让我们快速了解一下什么是路由:

somewebsite.com/someroute

somewebsite.com/someroute

It’s basically taking the user (or some data) from one place to another. That place is the route. I told you I was going to make it quick.

基本上是将用户(或一些数据)从一个地方转移到另一个地方。 那个地方就是路线。 我告诉过你,我要尽快。

创建项目 (Creating the project)

We’re going to build a fancy website to learn how routing works in Express. Check it out:

我们将建立一个精美的网站,以了解Express中路由的工作方式。 看看这个:

Cool, right? But it’s everything we need for the moment.

酷吧? 但这就是我们目前需要的一切。

First, let’s create the project and install the packages. Just run the following in the command line:

首先,让我们创建项目并安装软件包。 只需在命令行中运行以下命令:

npm install express

npm安装快递

npm install ejs

npm安装ejs

You can additionally add the dash dash save (I write — as “dash” because Medium automatically formats it, and it doesn’t look well for this purpose) to save it in your package.json file. But how this works is a story for another day.

您还可以添加破折号保存 (我写为“ 破折号”,因为中号会自动对其进行格式化,因此看起来不太理想),以将其保存在package.json文件中。 但是这如何工作又是另一回事了。

Then we will require Express and set the view engine to EJS in our app.js file as follows:

然后,我们将需要Express并在app.js文件中将视图引擎设置为EJS,如下所示:

var express = require('express');var app = express();app.set('view engine', 'ejs');

We’ll also include the following line so our app listens for requests:

我们还将包括以下行,以便我们的应用程序侦听请求:

app.listen(3000);

处理GET请求 (Handling GET requests)

Congratulations, everything is ready to handle requests! There are several types of requests in HTTP, but we’ll only be handling GET requests, which are used to retrieve data from the server. To handle this kind of request in Express, we use the following method:

恭喜,一切准备就绪,可以处理请求! HTTP中有几种类型的请求,但是我们仅处理GET请求,这些请求用于从服务器检索数据。 为了在Express中处理这种请求,我们使用以下方法:

app.get('/about', function(req, res) {  res.render('about');});

Let’s take a look at what’s happening here. We’re telling our server that, whenever someone types in somewebsite.com/about, we want to fire a function. That function takes two parameters, req (request) and res (response). Using the response object, we render the about page.

让我们看看这里发生了什么。 我们告诉服务器,每当有人键入somewebsite.com/about时 ,我们都想触发一个函数。 该函数有两个参数, req (请求)和res (响应)。 使用响应对象,我们呈现about页面

For this to work, we’ll have to create a page named about.ejs in HTML. We’ll also place it in a folder called views inside our project folder. This is the folder where Express will look to render the view. Here you have the mega-complex about page we’ll be using for this example:

为此,我们必须在HTML中创建一个名为about.ejs的页面。 我们还将其放置在项目文件夹中名为“ 视图”的文件夹中。 这是Express将在其中呈现视图的文件夹。 在这里,您将获得关于此示例的大型复杂页面:

Nice! But, what if the user doesn’t type in any route? Just like we do most of the times, somewebsite.com? Well, really easy. Change /about to just /, and render whatever page you like:

真好! 但是,如果用户不输入任何路径怎么办? 就像我们大多数时候一样, somewebsite.com吗? 好吧,真的很容易。 将/ about更改为/,然后呈现您喜欢的任何页面:

app.get('/', function(req, res) {  res.render('home');});

处理不存在的路线 (Handling non-existing routes)

But what if someone types in a route that doesn’t exist? We probably don’t want a default error page to show up. Instead, we want a custom, cool error page.

但是,如果有人输入不存在的路线怎么办? 我们可能不希望显示默认错误页面。 相反,我们需要一个自定义的很酷的错误页面。

Well, the good news is that it’s extremely easy to make one with Express. Just replace the route parameter in the get method with an asterisk and render your own error page like so:

好吧,好消息是,使用Express制作一个极其容易。 只需用星号替换get方法中的route参数,然后呈现自己的错误页面,如下所示:

app.get('*', function(req, res) {  res.render('error');});

试试吧! (Trying it out!)

Finally, let’s run our server from the command line (assuming the server is named app.js)

最后,让我们从命令行运行服务器(假设服务器名为app.js )

node app

节点应用

and see if it works! Let’s type in the name of our server (localhost, as it’s a local server running on our computer) and the port (3000 in this case) in our browser:

看看是否可行! 让我们在浏览器中输入服务器的名称( localhost ,因为它是在计算机上运行的本地服务器)和端口(在本例中为3000 ):

localhost:3000

本地主机:3000

Amazing!

惊人!

进一步阅读 (Further reading)

You can learn everything you need to know about routing in the Express guide, and there’s a lot of handy things in the EJS website as well!

您可以在Express指南中了解有关路由所需的所有知识,并且EJS网站上还有很多方便的事情!

I hope this article was helpful for you. If it was, please leave a comment and clap it up!

希望本文对您有所帮助。 如果是这样,请发表评论并鼓掌!

Happy coding… Or happy routing, I guess!

祝您编程愉快... 祝您路由愉快!

翻译自: https://www.freecodecamp.org/news/really-really-basic-routing-in-nodejs-with-express-d7cad5e3f5d5/

使用Express在Node.js中实现非常基本的路由相关推荐

  1. node mongoose_如何使用Express,Mongoose和Socket.io在Node.js中构建实时聊天应用程序

    node mongoose by Arun Mathew Kurian 通过阿伦·马修·库里安(Arun Mathew Kurian) 如何使用Express,Mongoose和Socket.io在N ...

  2. 如何在Node.js中退出

    用于退出的命令是什么? (即终止Node.js进程) #1楼 从命令行, .exit就是你想要的: $ node > .exit $ 它在REPL文档中有记录 . REPL(Read-Eval- ...

  3. Day 27: Restify —— 在Node.js中构建正确的REST Web服务

    今天决定学一个叫做restify的Node.js模块.restify模块使得在Node.js中写正确的REST API变得容易了很多,而且它还提供了即装即用的支持,如版本控制.错误处理.CORS和内容 ...

  4. node.js中的框架

    node.js中的框架 载自: http://nodeframework.com/ MVC frameworks Sinatra-like These frameworks offer rich co ...

  5. java 设置头错误信息,错误:在node.js中发送标头后无法设置标头

    我在node.js中写了这个简单的登录代码: var express = require ("express"); var badyparser = require (" ...

  6. node js fork php,Node.js中execFile,spawn,exec和fork简介

    Node.js中execFile,spawn,exec和fork简介 Node.js子流程child_process模块提供四种不同方法执行外部应用: 所有这些都是异步,调用这些方法会返回一个对象,这 ...

  7. Node.js中的不安全跳转如何防御详解

    为什么80%的码农都做不了架构师?>>>    Node.js中的不安全跳转如何防御详解 导语: 早年在浏览器大战期间,有远见的Chrome认为要运行现代Web应用,浏览器必须有一个 ...

  8. 在Node.js中,如何从其他文件中“包含”函数?

    假设我有一个名为app.js的文件. 很简单: var express = require('express'); var app = express.createServer(); app.set( ...

  9. 如何在Node.js中处理POST数据?

    如何提取Node.js中 HTTP POST方法发送的表单数据( form[method="post"] )和文件上传? 我已经阅读了文档,谷歌搜索并没有发现任何东西. funct ...

最新文章

  1. Mybatis入门:3(动态sql)
  2. 分享两篇Google Map API的介绍
  3. PVLAN技术应用,网络管理员的新宠
  4. 提高 DevTools 控制台调试 console 的 12 种方法
  5. interface关键字
  6. 括号配对问题(C++栈)
  7. 火狐 移动 html 元素,python中的Firefox+Selenium:如何交互式地获取元素html?
  8. 再见,余!额!宝!!!
  9. iCMS v8.0.0多终端内容管理系统
  10. 案例演示Python二维列表与Java二维数组
  11. 教学楼电梯调度需求分析
  12. cmd下dir后导入oracle数据库,Oracle在dos命令下导出导入
  13. 股东其实对公司情况一无所知,唯一办法是追责
  14. eclispe file查找
  15. 对话机器人技术简介:问答系统、对话系统与聊天机器人
  16. Oracle VS SAP
  17. “芝诺大数据教学科研平台”荣获“2018大数据应用优秀案例”
  18. Secondary NameNode:它究竟有什么作用?
  19. 10分钟读懂什么是产品定位
  20. 关于移动Web性能的五大神话

热门文章

  1. 解析底层原理!Android开发者面试如何系统复习?帮你突破瓶颈
  2. 自学Android!Android高级工程师面试题-字节跳动,附答案
  3. Java开发环境之RabbitMQ
  4. git 修改远程仓库源
  5. http://nancyfx.org + ASPNETCORE
  6. 51nod 1073约瑟夫环
  7. [转载] mysql 索引中的USING BTREE 的意义
  8. [leetcode] N-Queens II
  9. seo超强外部链接、内部链接技巧
  10. MySQL基础部分总结