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

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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394528.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机抄作通用模块,通用命令行模块的设计及实现

摘要:自从上个世纪八十年代以来,图形用户界面得到快速发展,计算机逐渐进入各类企业,家庭,其应用得到广泛的推广.对比起命令行界面来说,图形界面在交互性上有着不可比拟的优势.但在一些需要执行大量重复性工作的方面,例如在系统管理上,命令行界面提供的脚本功能,能够…

python读写磁盘扇区数据_C++-如何直接读取Windows磁盘扇区的数据?

1.通过CreateFile系列来完成读写扇区可以通过CreateFile打开磁盘逻辑分区,还要通过SetFilePointer以文件操作的方式把指针移到要操作的磁盘扇区开始处,在定位到要访问的扇区开始位置后就可以通过ReadFile或WriteFile函数实施相应的读写访问了&#xff0c…

公司 邮件 翻译 培训 长难句 结课

今天结课啦。。。。。。 明天培训总结,讲翻译技巧总结。 1new forms of thoughts as well as new subjects for thought must arise in the future as they have in the past, giving rise to new standards of elegance. 2if the small hot spots look as expected…

元祖(转载)

一.基本数据类型  整数:int  字符串:str(注:\t等于一个tab键)  布尔值: bool  列表:list   列表用[]  元祖:tuple  元祖用()  字典:dict注:所…

leetcood学习笔记-226- 翻转二叉树

题目描述: 第一次提交: class Solution(object):def invertTree(self, root):""":type root: TreeNode:rtype: TreeNode"""if not root:return Nonetemp root.leftroot.left root.rightroot.right temp# root.left,…

现代JavaScript中的精美图案:制冰厂

I’ve been working with JavaScript on and off since the late nineties. I didn’t really like it at first, but after the introduction of ES2015 (aka ES6), I began to appreciate JavaScript as an outstanding, dynamic programming language with enormous, expres…

惠普omen测试软件,双GTX1080奢华魔方PC 惠普OMEN X评测

惠普最近一段时间在游戏PC领域着力发力,桌面的暗影精灵家族热卖,如火如荼的势头终于传导到了台式机领域。而今,惠普也终于有了自己正统意义上的重型武器——桌面游戏台式机OMEN 900暗影精灵II 系列。今天我们就要为大家评测这款三万元的台式机…

python 清华镜像_Anaconda3清华镜像 V5.3.1 最新免费版

相关软件软件大小版本说明下载地址Anaconda3清华镜像是一款功能强大的python管理工具,此软件集成了Conda和Python等大量科学计算分析的包,可以帮助用户快速实现项目环境的配置,有需要的赶快来试试吧!【功能特点】1、省时省心&…

Qt第五课 无构造函数可以接受源类型,或构造函数重载决策不明确

场景QJsonArray rgParams { 10, 20, 30, 40 };编译代码的时候出错,C11标准才支持这种类的初始化列表语法,因此如果当前VS的版本过低,必须调整已有的代码,例子如下:QJsonArray rgParams;rgParams.insert(0, 10);rgPar…

二. linux基础命令

linux的基本命令一般有100多个,多练就可以了; 如果登陆用户是root,那么是#;如果是其他用户,则显示的是$ 练习:基本命令 1.创建一个目录/data mkdir /data ls -ld /data 2.在/data下面创建一个文件oldboy.tx…

mac 没有所有开发者_为什么开发人员应该像产品所有者那样思考

mac 没有所有开发者by Sajal Sarwar Sharma通过萨加尔萨瓦夏尔马 为什么开发人员应该像产品所有者那样思考 (Why developers should think more like product owners) You have just deployed your long-awaited feature to production after a long and gruesome month of co…

程序员这样对待简历,你期望面试官怎么对待你?

为什么想到谈这个问题呢? 前段时间公司因业务扩展需要招聘几个研发、运维以及测试人员,在看面试者的简历时,发现很多人都没有认真的去对待简历,只是把招聘网站上的打印一下就好了! 这就让我想问几个问题: 1…

mfc try catch 捕获并显示_“全栈2019”Java异常第十七章:Error该不该被捕获?

难度初级学习时间30分钟适合人群零基础开发语言Java开发环境JDK v11IntelliJ IDEA v2018.3友情提示本教学属于系列教学,内容具有连贯性,本章使用到的内容之前教学中都有详细讲解。本章内容针对零基础或基础较差的同学比较友好,可能对于有基础…

长春高中计算机考试时间安排,长春部分高中期末考试时间出炉!

原标题:长春部分高中期末考试时间出炉!上次跟大家分享了中小学的放假时间,今天就来说说期末考试时间吧!虽然有的学校时间未定,但是按照惯例,长春市各大高中高一高二年级,本次的期末考试时间&…

用习惯了windows系统要怎样去认识linux系统(一)

一、前言对于普通用户来说99%都使用的是windows操作系统,即便那些会使用linux系统的技术员来说,他们PC上安装的也是windows系统。linux系统只是用于服务器市场,可以说现在服务器市场80%使用的是linux系统。那它们两系统之间有哪些区别呢&…

spring 配置文件模板

<?xml version"1.0" encoding"UTF-8"?><beans xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc"http://www.springframework.org/schema/mvc" xmlns:context"http://www.springframework.org/schema…

VAssistX使用小窍门

日常使用中的一些VAssistX使用小窍门&#xff0c;简单总结下 一&#xff0c;修改VAssistX默认缓存文件路径&#xff0c;防止默认C盘被占用空间过大 1、 打开注册表HKCU\Software\Whole Tomato&#xff0c;新建UserDataDir&#xff0c;数值为要修改的路径&#xff0c;如下图&am…

react 交互_如何在React应用程序中跟踪用户交互

react 交互by Faouzi Oudouh通过Faouzi Oudouh 如何在React应用程序中跟踪用户交互 (How to track user interactions in your React app) Worry not about which Analytics provider you need to gather user interaction within your app.不必担心需要哪个Analytics(分析)提…

shell python比较_shell中的条件判断以及与python中的对比

shell中比如比较字符串、判断文件是否存在及是否可读等&#xff0c;通常用"[]"来表示条件测试。注意&#xff1a;这里的空格很重要。要确保方括号的空格。if ....; then python中的条件判断&#xff1a; if ....: (此处是冒号&#xff0c;不同…

服务器麒麟系统能设置mtu吗,麒麟操作系统安装标准手册-20210405220006.docx-原创力文档...

精品文档精品文档PAGEPAGE47精品文档PAGE.银河麒麟V3操作系统安装手册V1.2编制&#xff1a;王帅校核&#xff1a;朱本亮审定&#xff1a;周俊...文档更新日志&#xff1a;序号修订时间修订内容修改人审定人012017-04-12发布文档V1.0王帅周俊022017-05-11增加启动安装时蓝屏错误…