使用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.pswp.cn/news/394528.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394528.shtml
英文地址,請注明出處:http://en.pswp.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增加啟動安裝時藍屏錯誤…