使用Express和MongoDB構建簡單的CRUD應用程序

by Zell Liew

由Zell Liew

使用Express和MongoDB構建簡單的CRUD應用程序 (Building a Simple CRUD Application with Express and MongoDB)

For a long time, I didn’t dare venture into back end development. I felt intimidated because of my lack of an academic background in programming.

很長一段時間,我都不敢冒險進行后端開發。 由于缺乏編程方面的學術背景,我感到膽怯。

I remember when I eventually built up the courage to try back end development. I had such a hard time understanding the documentation for Express, MongoDB, and Node.js that I gave up.

我記得當我最終鼓起勇氣嘗試后端開發時。 我很難理解我放棄的Express,MongoDB和Node.js的文檔。

I eventually went back and worked through my confusion. Now, one year later, I understood how to work with these tools. So, I decided to write this comprehensive tutorial so you won’t have to go through the same headache that I went through.

我最終回過頭來,度過了困惑。 一年后的現在,我了解了如何使用這些工具。 因此,我決定編寫此綜合教程,這樣您就不必再經歷與我經歷的同樣的頭痛了。

CRUD,Express和MongoDB (CRUD, Express and MongoDB)

CRUD, Express and MongoDB are big words for a person who has never touched any server-side programming in their life. Let’s quickly introduce what they are before we diving into the tutorial.

對于一個從未接觸過任何服務器端編程的人來說,CRUD,Express和MongoDB是個好話。 在深入學習本教程之前,讓我們快速介紹一下它們是什么。

Express is a framework for building web applications on top of Node.js. It simplifies the server creation process that is already available in Node. In case you were wondering, Node allows you to use JavaScript as your server-side language.

Express是一個用于在Node.js之上構建Web應用程序的框架。 它簡化了Node中已經可用的服務器創建過程。 如果您想知道,Node允許您將JavaScript用作服務器端語言。

MongoDB is a database. This is the place where you store information for your web websites (or applications).

MongoDB是一個數據庫。 這是您存儲網站(或應用程序)信息的地方。

CRUD is an acronym for Create, Read, Update and Delete. It is a set of operations we get servers to execute (POST, GET, PUT and DELETE respectively). This is what each operation does:

CRUD是創建,讀取,更新和刪除的首字母縮寫。 這是我們讓服務器執行的一組操作(分別是POST,GET,PUT和DELETE)。 這是每個操作的作用:

  • Create (POST) — Make something

    創建(POST) -做點什么

  • Read (GET)_- Get something

    讀(GET) _-得到一些東西

  • Update (PUT) — Change something

    更新(PUT) -更改某些內容

  • Delete (DELETE)– Remove something

    刪除(刪除) –刪除某些內容

If we put CRUD, Express and MongoDB together into a single diagram, this is what it would look like:

如果將CRUD,Express和MongoDB放到一個圖表中,它將是這樣的:

Does CRUD, Express and MongoDB makes more sense to you now?

CRUD,Express和MongoDB現在對您有意義嗎?

Great. Let’s move on.

大。 讓我們繼續。

我們正在建立的 (What we’re building)

We’re going to build an application simple list application that allows you to keep track of things within a list (like a Todo List for example).

我們將構建一個簡單的應用程序列表應用程序,使您可以跟蹤列表中的內容(例如Todo List)。

Well, a todo list is kind of boring. How about we make a list of quotes from Star wars characters instead? Awesome, isn’t it? Feel free to take a quick look at the demo before continuing with the tutorial. Also, this is where you can find the finished code for the application.

好吧,待辦事項清單有點無聊。 我們如何列出《星球大戰》角色的報價單呢? 太好了,不是嗎? 在繼續學習本教程之前,請隨時快速瀏覽一下該演示 。 另外, 在這里您可以找到應用程序的完成代碼。

By the way, what we’re building isn’t a sexy single page app. We’re mainly focusing on how to use CRUD, Express and Mongo DB in this tutorial, so, more server-side stuff. I’m not going to emphasize style.

順便說一句,我們正在構建的并不是一個性感的單頁應用程序。 在本教程中,我們主要側重于如何使用CRUD,Express和Mongo DB,因此,還有更多服務器端內容。 我不會強調風格。

You’ll need two things to get started with this tutorial:

您將需要兩件事來開始本教程:

  1. You shouldn’t be afraid of typing commands into a shell. Check out this article if you currently are.

    您不必擔心在shell中鍵入命令。 如果您當前正在查看這篇文章 。

  2. You need to have Node installed.

    您需要安裝Node 。

To check if you have Node installed, open up your command line and run the following code:

要檢查是否已安裝Node,請打開命令行并運行以下代碼:

$ node -v

You should get a version number if you have Node installed. If you don’t, you can install Node either by downloading the installer from Node’s website or downloading it through package managers like Homebrew (Mac) and Chocolatey (Windows).

如果安裝了Node,則應該獲得版本號。 如果不這樣做,則可以通過從Node網站下載安裝程序或通過Homebrew (Mac)和Chocolatey (Windows)等程序包管理器下載Node來安裝Node。

入門 (Getting started)

Start by creating a folder for this project. Feel free to call it anything you want. Once you navigate into it, run the npm init command.

首先為該項目創建一個文件夾。 隨時隨地調用它即可。 導航到它之后,運行npm init命令。

This command creates a package.json file which helps you manage dependencies that we install later in the tutorial.

該命令將創建一個package.json文件,該文件可幫助您管理我們稍后將在本教程中安裝的依賴項。

$ npm init

Just hit enter through everything that appears. I’ll talk about the ones you need to know as we go along.

只需按Enter即可出現的所有內容。 我將在討論過程中談論您需要了解的內容。

一生中第一次運行Node (Running Node for the first time in your life)

The simplest way to use node is to run the node command, and specify a path to a file. Let’s create a file called server.js to run node with.

使用節點的最簡單方法是運行node命令,并指定文件的路徑。 讓我們創建一個名為server.js的文件以運行node。

$ touch server.js

When the execute the server.js file, we want to make sure it’s running properly. To do so, simply write a console.log statement in server.js:

執行server.js文件時,我們要確保其運行正常。 為此,只需在server.js中編寫console.log語句:

console.log('May Node be with you')

Now, run node server.js in your command line and you should see the statement you logged:

現在,在命令行中運行node server.js,您應該看到記錄的語句:

Great. Let’s move on and learn how to use Express now.

大。 讓我們繼續學習現在如何使用Express。

使用快遞 (Using Express)

We first have to install Express before we can use it in our application. Installing Express is pretty easy. All we have to do is run an install command with Node package manager (npm),which comes bundled with Node.

我們必須先安裝Express,然后才能在應用程序中使用它。 安裝Express非常簡單。 我們要做的就是使用Node軟件包管理器(npm)運行安裝命令,該軟件包與Node捆綁在一起。

Run the npm install express — save command in your command line:

運行npm install express —在命令行中保存命令:

$ npm install express --save

Once you’re done, you should see that npm has saved Express as a dependency in package.json.

完成后,您應該看到npm已將Express保存為package.json中的依賴項。

Next, we use express in server.js by requiring it.

接下來,我們通過要求在server.js中使用express。

const express = require('express');const app = express();

The first thing we want to do is to create a server where browsers can connect to. We can do so with the help of a listen method provided by Express:

我們要做的第一件事是創建一個瀏覽器可以連接到的服務器。 我們可以借助Express提供的listen方法來做到這一點:

app.listen(3000, function() {  console.log('listening on 3000')})

Now, run node server.js and navigate to localhost:3000 on your browser. You should see a message that says “cannot get /”.

現在,運行節點server.js并在瀏覽器上導航到localhost:3000。 您應該看到一條消息“無法獲取/”。

That’s a good sign. It means we can now communicate to our express server through the browser. This is where we begin CRUD operations.

這是一個好兆頭。 這意味著我們現在可以通過瀏覽器與快遞服務器通信 。 這是我們開始CRUD操作的地方。

CRUD —閱讀 (CRUD — READ)

The READ operation is performed by browsers whenever you visit a webpage. Under the hood, browsers sends a GET request to the server to perform a READ operation. The reason we see the “cannot get /” error is because we have yet to send anything back to the browser from our server.

每當您訪問網頁時,瀏覽器都會執行READ操作。 在后臺,瀏覽器將GET請求發送到服務器以執行READ操作。 我們看到“無法獲取/”錯誤的原因是因為我們尚未將任何內容從服務器發送回瀏覽器。

In Express, we handle a GET request with the get method:

在Express中,我們使用get方法處理GET請求:

app.get(path, callback)

The first argument, path, is the path of the GET request. It’s anything that comes after your domain name.

第一個參數path是GET請求的路徑。 域名之后的任何內容。

When we’re visiting localhost:3000, our browsers are actually looking for localhost:3000/. The path argument in this case is /.

當我們訪問localhost:3000時,我們的瀏覽器實際上正在尋找localhost:3000 /。 在這種情況下,路徑參數為/。

The second argument is a callback function that tells the server what to do when the path is matched. It takes in two arguments, a request object and a response object:

第二個參數是一個回調函數 ,它告訴服務器當路徑匹配時該怎么做。 它接受兩個參數,一個請求對象和一個響應對象:

app.get('/', function (request, response) {  // do something here})

For now, let’s write “Hello World” back to the browser. We do so by using a send method that comes with the response object:

現在,讓我們將“ Hello World”寫回到瀏覽器。 為此,我們使用了響應對象隨附的send方法:

app.get('/', function(req, res) {  res.send('Hello World')})// Note: request and response are usually written as req and res respectively.

I’m going to start writing in ES6 code and show you how to convert to ES6 along the way as well. First off, I’m replacing the function() with the ES6 arrow function. The below code is the same as the above code:

我將開始編寫ES6代碼,并向您展示如何轉換為ES6。 首先,我要用ES6箭頭函數替換function()。 下面的代碼與上面的代碼相同:

app.get('/', (req, res) => {  res.send('hello world')})

Now, restart your server by doing the following:

現在,通過執行以下操作重新啟動服務器:

  1. Stop the current server by hitting CTRL + C in the command line.

    通過在命令行中按CTRL + C來停止當前服務器。
  2. Run node server.js again.

    再次運行節點server.js。

Then, navigate to localhost:3000 on your browser. You should be able to see a string that says “Hello World”.

然后,在瀏覽器上導航到localhost:3000。 您應該能夠看到顯示“ Hello World”的字符串。

Great. Let’s change our app so we serve an index.html page back to the browser instead. To do so, we use the sendFile method that’s provided by the res object.

大。 讓我們更改應用程序,以便將index.html頁面提供回瀏覽器。 為此,我們使用res對象提供的sendFile方法。

app.get('/', (req, res) => {  res.sendFile(__dirname + '/index.html')  // Note: __dirname is the path to your current working directory. Try logging it and see what you get!   // Mine was '/Users/zellwk/Projects/demo-repos/crud-express-mongo' for this app.})

In the sendFile method above, we told Express to serve an index.html file that can be found in the root of your project folder. We don’t have that file yet. Let’s make it now.

在上面的sendFile方法中,我們告訴Express提供一個index.html文件,該文件可以在您的項目文件夾的根目錄中找到。 我們還沒有那個文件。 現在開始吧。

touch index.html

Let’s put some text in our index.html file as well:

我們也將一些文本放入我們的index.html文件中:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>MY APP</title></head><body>  May Node and Express be with you.   </body></html>

Restart your server and refresh your browser. You should be able to see the results of your HTML file now.

重新啟動服務器并刷新瀏覽器。 您現在應該可以看到HTML文件的結果。

This is how Express handles a GET request (READ operation) in a nutshell.

簡而言之,這就是Express處理GET請求( READ操作)的方式。

At this point, you probably have realized that you need to restart your server whenever you make a change to server.js. This is process is incredibly tedious, so let’s take a quick detour and streamline it by using a package called nodemon.

至此,您可能已經意識到,只要更改server.js,就需要重新啟動服務器。 這個過程非常繁瑣,因此讓我們快速繞道并使用一個名為nodemon的包來簡化它。

輸入Nodemon (Enter Nodemon)

Nodemon restarts the server automatically whenever you save a file that the server uses. We can install Nodemon by using the following command:

每當您保存服務器使用的文件時, Nodemon都會自動重新啟動服務器。 我們可以使用以下命令來安裝Nodemon:

$ npm install nodemon --save-dev

Note: The reason we’re using a — save-dev flag here is because we’re only using Nodemon when we’re developing. This flag would save Nodemon as a devDependency in your package.json file.

注意:我們在這里使用一個save-dev標志的原因是因為我們僅在開發時使用Nodemon。 此標志會將Nodemon保存為package.json文件中的devDependency。

Moving on, Nodemon behaves exactly the same as node, which means we can run our server by calling nodemon server.js. However, we can’t do it in the command line right now because Nodemon isn’t installed with a -g flag.

接下來,Nodemon的行為與節點完全相同,這意味著我們可以通過調用nodemon server.js來運行服務器。 但是,由于Nodemon未安裝-g標志,因此我們現在無法在命令行中執行此操作。

There’s one other way to run Nodemon — we can execute Nodemon from the node_modules folder. The code looks like this:

還有另一種運行Nodemon的方法-我們可以從node_modules文件夾執行Nodemon。 代碼如下:

$ ./node_modules/.bin/nodemon server.js

That’s a handful to type. One way to make it simpler is to create a script key in package.json.

鍵入很少。 一種簡化的方法是在package.json中創建腳本密鑰。

{  // ...   "scripts": {    "dev": "nodemon server.js"  }  // ...}

Now, you can run npm run dev to trigger nodemon server.js.

現在,您可以運行npm run dev來觸發nodemon server.js。

Back to the main topic. We’re going to cover the CREATE operation next.

回到主要話題。 接下來,我們將介紹CREATE操作。

CRUD —創建 (CRUD — CREATE)

The CREATE operation is performed only by the browser if a POST request is sent to the server. This POST request can triggered either with JavaScript or through a <form> element.

如果將POST請求發送到服務器,則僅由瀏覽器執行CREATE操作。 可以使用JavaScript或通過<form>元素觸發此POST請求。

Let’s find out how to use a <form> element to create new entries for our star wars quote app for this part of the tutorial.

讓我們找出如何使用<form>元素為教程的這一部分為我們的《星球大戰》報價應用程序創建新條目。

To do so, you first have to create a <form> element and add it to your index.html file. You need to have three things on this form element:

為此,您首先必須創建一個<form>元素并將其添加到index.html文件中。 您需要在此表單元素上包含三件事:

  1. An action attribute

    動作屬性
  2. a method attribute

    方法屬性
  3. and name attributes on all <input> elements within the form

    和名稱屬性在表單中的所有<input>元素上
<form action="/quotes" method="POST">  <input type="text" placeholder="name" name="name">  <input type="text" placeholder="quote" name="quote">  <button type="submit">Submit</button></form>

The action attribute tells the browser where to navigate to in our Express app. In this case, we’re navigating to /quotes. The method attribute tells the browser what to request to send. In this case, it’s a POST request.

action屬性告訴瀏覽器在我們Express應用中的導航位置。 在這種情況下,我們導航到/ quotes。 method屬性告訴瀏覽器要發送什么請求。 在這種情況下,這是一個POST請求。

On our server, we can handle this POST request with a post method that Express provides. It takes the same arguments as the GET method:

在我們的服務器上,我們可以使用Express提供的post方法處理該POST請求。 它采用與GET方法相同的參數:

app.post('/quotes', (req, res) => {  console.log('Hellooooooooooooooooo!')})

Restart your server (hopefully you’ve set up Nodemon so it restarts automatically) and refresh your browser. Then, enter something into your form element. You should be able to see Hellooooooooooooooooo! in your command line.

重新啟動服務器(希望您已設置Nodemon,使其自動重新啟動)并刷新瀏覽器。 然后,在表單元素中輸入一些內容。 您應該能夠看到Hellooooooooooooooooo! 在您的命令行中。

Great, we know that Express is handling the form for us right now. The next question is, how do we get the input values with Express?

太好了,我們知道Express正在為我們處理表格。 下一個問題是,如何使用Express獲得輸入值?

Turns out, Express doesn’t handle reading data from the <form> element on it’s own. We have to add another package called body-parser to gain this functionality.

事實證明,Express本身并不處理從<form>元素讀取數據。 我們必須添加另一個程序包主體分析器才能獲得此功能。

$ npm install body-parser --save

Express allows us to add middlewares like body-parser to our application with the use method. You’ll hear the term middleware a lot when dealing with Express. These things are basically plugins that change the request or response object before they get handled by our application. Make sure you place body-parser before your CRUD handlers!

Express允許我們使用use方法向我們的應用程序中添加諸如body-parser之類的中間件。 在處理Express時,您會聽到很多術語“中間件”。 這些東西基本上是在我們的應用程序處理它們之前更改請求或響應對象的插件。 確保將正文解析器放在CRUD處理程序之前!

const express = require('express')const bodyParser= require('body-parser')const app = express()
app.use(bodyParser.urlencoded({extended: true}))
// All your handlers here...

The urlencoded method within body-parser tells body-parser to extract data from the <form> element and add them to the body property in the request object.

body-parser中的urlencoded方法告訴body-parser從<form>元素中提取數據并將其添加到請求對象的body屬性中。

Now, you should be able to see everything in the form field within the req.body object. Try doing a console.log and see what it is!

現在,您應該能夠在req.body對象內的form字段中看到所有內容。 嘗試做一個console.log,看看它是什么!

app.post('/quotes', (req, res) => {  console.log(req.body)})

You should be able to get an object similar to the following in your command line:

您應該能夠在命令行中獲得類似于以下內容的對象:

Hmmm. Master Yoda has spoken! Let’s make sure we remember Yoda’s words. It’s important. We want to be able to retrieve it the next time we load our index page.

嗯 尤達大師講話! 讓我們確保我們記得尤達的話。 這一點很重要。 我們希望下次加載索引頁面時能夠檢索它。

Enter the database, MongoDB.

輸入數據庫MongoDB。

MongoDB (MongoDB)

We first have to install MongoDB through npm if we want to use it as our database.

如果要使用MongoDB作為數據庫,首先必須通過npm安裝它。

npm install mongodb --save

Once installed, we can connect to MongoDB through the Mongo.Client‘s connect method as shown in the code below:

安裝后,我們可以通過Mongo.Client的connect方法連接到MongoDB,如下代碼所示:

const MongoClient = require('mongodb').MongoClient
MongoClient.connect('link-to-mongodb', (err, database) => {  // ... start the server})

The next part is to get the correct link to our database. Most people store their databases on cloud services like MongoLab. We’re going to do same as well.

下一部分是獲得到我們數據庫的正確鏈接。 大多數人將其數據庫存儲在MongoLab等云服務上。 我們也將做同樣的事情。

So, go ahead and create an account with MongoLab. (It’s free). Once you’re done, create a new MongoDB Deployment and set the plan to sandbox.

因此,繼續使用MongoLab創建一個帳戶。 (免費)。 完成后,創建一個新的MongoDB部署并將計劃設置為沙箱。

Once you’re done creating the deployment, head into it and create a database user and database password. Remember the database user and database password because you’re going to use it to connect the database you’ve just created.

創建完部署后,請進入部署并創建數據庫用戶和數據庫密碼。 記住數據庫用戶和數據庫密碼,因為您將使用它來連接剛剛創建的數據庫。

Finally, grab the MongoDB url and add it to your MongoClient.connect method. Make sure you use your database user and password!

最后,獲取MongoDB網址并將其添加到您的MongoClient.connect方法中。 確保使用數據庫用戶名和密碼!

MongoClient.connect('your-mongodb-url', (err, database) => {  // ... do something here})

Next, we want to start our servers only when the database is connected. Hence, let’s move app.listen into the connect method. We’re also going to create a db variable to allow us to use the database when we handle requests from the browser.

接下來,我們只想在連接數據庫時啟動服務器。 因此,讓我們將app.listen移到connect方法中。 我們還將創建一個db變量,以允許我們在處理來自瀏覽器的請求時使用數據庫。

var db
MongoClient.connect('your-mongodb-url', (err, database) => {  if (err) return console.log(err)  db = database  app.listen(3000, () => {    console.log('listening on 3000')  })})

We’re done setting up MongoDB. Now, let’s create a quotes collection to store quotes for our application.

我們已經完成了MongoDB的設置。 現在,讓我們創建一個quotes集合來存儲我們的應用程序的報價。

By the way, a collection is a named location to store stuff. You can create as many collections as you want. It can be things like “products”, “quotes”, “groceries”, or any other labels you choose.

順便說一句, 集合是存儲東西的命名位置 。 您可以根據需要創建任意多個集合。 可以是諸如“產品”,“報價”,“雜貨”或您選擇的任何其他標簽之類的東西。

We can create the quotes collection by using the string quotes while calling MongoDB’s db.collection() method. While creating the quotes collection, we can also save our first entry into MongoDB with the save method simultaneously.

我們可以在調用MongoDB的db.collection()方法時使用字符串引號創建引號集合。 在創建報價集合時,我們還可以使用save方法將第一個條目同時保存到MongoDB中。

Once we’re done saving, we have to redirect the user somewhere (or they’ll be stuck waiting forever for our server to move). In this case, we’re going to redirect them back to /, which causes their browsers to reload.

保存完成后,我們必須將用戶重定向到某個位置 (否則,他們將永遠被困在等待服務器移動的位置)。 在這種情況下,我們將其重定向回/,這將導致其瀏覽器重新加載。

app.post('/quotes', (req, res) => {  db.collection('quotes').save(req.body, (err, result) => {    if (err) return console.log(err)
console.log('saved to database')    res.redirect('/')  })})

Now, if you enter something into the <form> element, you’ll be able to see an entry in your MongoDB collection.

現在,如果您在<form>元素中輸入內容,您將能夠在MongoDB集合中看到一個條目。

Whoohoo! Since we already have some quotes in the collection, why not try showing them to our user when they land on our page?

hoo! 既然我們已經在集合中包含了一些報價,那么為什么不嘗試在用戶登陸我們的頁面時將其顯示給用戶呢?

向用戶顯示報價 (Showing quotes to users)

We have to do two things to show the quotes stored in MongoLab to our users.

我們必須做兩件事才能向用戶顯示MongoLab中存儲的報價。

  1. Get quotes from MongoLab

    獲得MongoLab的報價
  2. Use a template engine to display the quotes

    使用模板引擎顯示報價

Let’s go one step at a time.

讓我們一次走一步。

We can get the quotes from MongoLab by using the find method that’s available in the collection method.

我們可以使用collection方法中可用的find方法從MongoLab獲取報價。

app.get('/', (req, res) => {  var cursor = db.collection('quotes').find()})

The find method returns a cursor (A Mongo Object) that probably doesn’t make sense if you console.log it out.

find方法返回一個游標(一個Mongo對象),如果您進行console.log out,則該游標可能沒有任何意義。

The good news is, this cursor object contains all quotes from our database. It also contains a bunch of other properties and methods that allow us to work with data easily. One such method is the toArray method.

好消息是,此游標對象包含我們數據庫中的所有引號。 它還包含許多其他屬性和方法,這些屬性和方法使我們可以輕松地處理數據。 一種這樣的方法是toArray方法。

The toArray method takes in a callback function that allows us to do stuff with quotes we retrieved from MongoLab. Let’s try doing a console.log() for the results and see what we get!

toArray方法帶有一個回調函數,該函數允許我們使用從MongoLab檢索到的引號進行處理。 讓我們嘗試對結果進行console.log()看看我們得到了什么!

db.collection('quotes').find().toArray(function(err, results) {  console.log(results)  // send HTML file populated with quotes here})

Great! You now see an array of quotes (I only have one right now). We’ve completed the first part — getting data from MongoLab. The next part is to generate a HTML that contains all our quotes.

大! 現在,您會看到一組引號(我現在只有一個)。 我們已經完成了第一部分-從MongoLab獲取數據。 下一部分是生成包含所有引號HTML。

We can’t serve our index.html file and expect quotes to magically appear because there’s no way to add dynamic content to a HTML file. What we can do instead, is to use template engines to help us out. Some popular template engines include Jade, Embedded JavaScript and Nunjucks.

我們無法提供index.html文件,不能期望引號神奇地出現,因為無法將動態內容添加到HTML文件中。 我們可以做的是使用模板引擎來幫助我們。 一些流行的模板引擎包括Jade,嵌入式JavaScript和Nunjucks。

I’ve written extensively about the how and why of template engines in a separate post. You might want to check it out if you have no idea what template engines are. I personally use (and recommend) Nunjucks as my template engine of choice. Feel free to check out the post to find out why.

我在另一篇文章中廣泛地介紹了模板引擎的方式和原因。 如果您不知道什么是模板引擎,則可能需要檢查一下。 我個人使用(并推薦)Nunjucks作為我選擇的模板引擎。 隨時查看該帖子以了解原因。

For this tutorial, we’re going to use Embedded JavaScript (ejs) as our template engine because it’s the easiest to start with. You’ll find it familiar from the get-go since you already know HTML and JavaScript.

在本教程中,我們將使用嵌入式JavaScript (ejs)作為模板引擎,因為它是最簡單的開始。 從一開始,您就會發現它很熟悉,因為您已經了解HTML和JavaScript。

We can use EJS by first installing it, then setting the view engine in Express to ejs.

我們可以先安裝EJS,然后將Express中的視圖引擎設置為ejs來使用。

$ npm install ejs --save
app.set('view engine', 'ejs')

Once the view engine is set, we can begin generating the HTML with our quotes. This process is also called rendering. We can use the render object built into the response object render to do so. It has the following syntax:

設置視圖引擎后,我們就可以開始使用引號來生成HTML了。 此過程也稱為渲染 。 我們可以使用內置在響應對象render中的render對象來做到這一點。 它具有以下語法:

res.render(view, locals)

The first parameter, views, is the name of the file we’re rendering. This file must be placed within a views folder.

第一個參數views是我們正在渲染的文件的名稱。 該文件必須放置在views文件夾中。

The second parameter, locals, is an object that passes data into the view.

第二個參數locals是一個將數據傳遞到視圖的對象。

Let’s first create an index.ejs file within the views folder so we can start populating data.

首先讓我們在views文件夾中創建一個index.ejs文件,以便我們可以開始填充數據。

$ mkdir views$ touch views/index.ejs

Now, place the following code within index.ejs.

現在,將以下代碼放入index.ejs中。

<ul class="quotes">  <% for(var i=0; i<quotes.length; i++) {%>    <li class="quote">      <span><%= quotes[i].name %></span>      <span><%= quotes[i].quote %></span>    </li>  <% } %></ul>

See what I mean when I say you’ll find it familiar? In EJS, you can write JavaScript within <% and %> tags. You can also output JavaScript as strings if you use the <%= and %> tags.

明白當我說您會覺得熟悉時的意思嗎? 在EJS中,您可以在<%和%>標記內編寫JavaScript。 如果使用<%=和%>標記,還可以將JavaScript輸出為字符串。

Here, you can see that we’re basically looping through the quotes array and create strings with quotes[i].name and quotes[i].quote.

在這里,您可以看到我們基本上遍歷了quotes數組,并創建了帶有quotes [i] .name和quotes [i] .quote的字符串。

One more thing to do before we move on from the index.ejs file. Remember to copy the <form> element from the index.html file into this file as well. The complete index.ejs file so far should be:

從index.ejs文件繼續之前,還有另一件事要做。 切記也將<form>元素也從index.html文件復制到該文件中。 到目前為止,完整的index.ejs文件應為:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>MY APP</title></head><body>  May Node and Express be with you.
<ul class="quotes">  <% for(var i=0; i<quotes.length; i++) {%>    <li class="quote">      <span><%= quotes[i].name %></span>      <span><%= quotes[i].quote %></span>    </li>  <% } %>  </ul>
<form action="/quotes" method="POST">    <input type="text" placeholder="name" name="name">    <input type="text" placeholder="quote" name="quote">    <button type="submit">Submit</button>  </form></body></html>

Finally, we have to render this index.ejs file when handling the GET request. Here, we’re setting the results (an array) as the quotes array we used in index.ejs above.

最后,我們必須在處理GET請求時呈現此index.ejs文件。 在這里,我們將結果(一個數組)設置為上面index.ejs中使用的引號數組。

app.get('/', (req, res) => {  db.collection('quotes').find().toArray((err, result) => {    if (err) return console.log(err)    // renders index.ejs    res.render('index.ejs', {quotes: result})  })})

Now, refresh your browser and you should be able to see Master Yoda’s quotes.

現在,刷新瀏覽器,您應該能夠看到Yoda大師的報價。

Um. You maybe only have one quote if you followed the tutorial step by step until this point. The reason I have multiple quotes is because I silently added more as I worked on the application.

嗯 如果您逐步按照本教程進行操作,則可能只有一個報價。 我有多個引號的原因是因為我在處理該應用程序時默默地添加了更多內容。

結語 (Wrapping Up)

We’ve covered a lot of ground in just 3000 words. Here are a few bullets to sum it all up. You have…

我們僅用3000個字就覆蓋了很多領域。 這里總結了一些項目符號。 你有…

  • Created an Express Server

    創建一個Express服務器
  • Learned to execute CREATE and READ operations

    學習執行CREATE和READ操作
  • Learned to save and read from MongoDB

    學會保存和從MongoDB中讀取
  • Learned to use a template engine like Embedded JS.

    了解如何使用模板引擎,例如Embedded JS。

There are two more operations to go, but we’ll leave it to the next post. Catch you there!

還有兩個操作要做,但我們將其留在下一篇文章中。 趕上你!

This article first appeared on my blog at www.zell-weekeat.com. Check it out if you want more articles like this

這篇文章首先出現在我的博客www.zell-weekeat.com上 。 如果您想要更多這樣的文章,請查看

翻譯自: https://www.freecodecamp.org/news/building-a-simple-crud-application-with-express-and-mongodb-63f80f3eb1cd/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/396471.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396471.shtml
英文地址,請注明出處:http://en.pswp.cn/news/396471.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python元類的使用_python中元類用法實例

本文實例講述了python中元類用法&#xff0c;分享給大家供大家參考。具體方法分析如下&#xff1a;1.元類(metaclass)是用來創建類的類2.type(object):返回一個對象的類型&#xff0c;與object.__class__的值相同&#xff0c;type(name,bases,dict):創建一個新的type類型&#…

使用uicollectionView時需要注意的問題

1.UICollectionView使用流水布局——UICollectionViewFlowLayout時&#xff0c;需要滿足條件&#xff1a; 每個item(即cell)的大小是一樣的&#xff0c;不僅是寬度&#xff0c;還有高度。這樣&#xff0c;當collectionview的寬度發生變化時&#xff0c;item能將其動態填充。ite…

hiveql函數筆記(二)

1、數據查詢 //提高聚合的性能 SET hive.map.aggrtrue; SELECT count(*),avg(salary) FROM employees; //木匾不允許在一個查詢語句中使用多于一個的函數&#xff08;DISTINCT。。。&#xff09;表達式 SELECT count(DISTINCT symbol) FROM stocks; 表生成函數&#xff1a; exp…

jQuery 常用的方法

<!DOCTYPE html><html lang"en"><head> <meta charset"utf-8"/> <title>品牌列表案例</title> <script src"js/jquery-2.1.1.min.js" rel"script"></script> <script…

swift 從手機選照片_19元起!定制專屬手機殼!還可免費打印照片...

△劇透&#xff1a;文末有福利現在的年輕人體內涌動的都是追求有趣有特色的靈魂希望自己是這條gai最獨一無二的仔撞衫撞包撞手機殼可以說是當代年輕人三大時尚忌諱尤其是手機殼極為重要畢竟換殼≈換機只需要幾十元買新殼就可以擁有換新機般的儀式感不過作為手機殼老手都知道在某…

新手也能學會本地調試微信,natapp 官網映射

本地調試微信的新手指引~ 照著配置&#xff0c;一定可以配置成功&#xff0c;實現本地調試微信&#xff0c;公司好幾個同事按照我寫的步驟&#xff0c;都獨立配成功了。 1.首選在natapp注冊一個賬號&#xff0c;申請免費隧道或者購買隧道&#xff0c;我買了一個月9元的付費隧道…

在JavaScript中反轉字符串的三種方法

This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”本文基于Free Code Camp基本算法腳本“ Reverse a String ” Reversing a string is one of the most frequently asked JavaScript question in the technical round of interview. …

c實現三角形角度大于一個值_初中數學三角形知識點小結

▊ 三角形兩邊定理&#xff1a;三角形兩邊的和大于第三邊。推論&#xff1a;三角形兩邊的差小于第三邊。▊ 三角形中位線定理三角形的中位線平行于第三邊&#xff0c;并且等于它的一半。▊ 三角形的重心三角形的重心到頂點的距離是它到對邊中點距離的2倍。在三角形中&#x…

【Spring】使用Spring和AMQP發送接收消息(下)

為什么80%的碼農都做不了架構師&#xff1f;>>> 上篇講了RabbitMQ連接工廠的作用是用來創建RabbitMQ的連接&#xff0c;本篇就來講講RabbitMQ的發送消息。通過RabbitMQ發送消息最簡單的方式就是將connectionFactory Bean注入到服務層類中&#xff0c;并使用它創建C…

微軟u盤安裝工具_使用微軟Winget工具安裝軟件教程

對于系統管理員來說&#xff0c;一款好用的軟件包管理工具可以大大提高安裝、部署、管理軟件的效率。可之前只有 MscOS 和 Linux 官方才有軟件包管理工具&#xff0c;微軟官方現在終于為Windows系統發布了一款名為Winget的軟件包管理工具&#xff0c;MS酋長下面就來為大家演示一…

ZOJ2930 The Worst Schedule(最小割)

題目大概說有n個任務&#xff0c;每個任務可以提前或推遲&#xff0c;提前或推遲各有一定的費用&#xff0c;有的任務一旦推遲另一個任務也必須推遲&#xff0c;問怎么安排任務使花費最少&#xff0c;且最少花費的條件下提前的任務數最多能多少。 問題就是要把各個任務分成兩個…

為什么要free釋放內存_為什么在Free Code Camp上列出一份工作要花1,000美元?

為什么要free釋放內存by Michael D. Johnson邁克爾約翰遜(Michael D.Johnson) 為什么在Free Code Camp上列出一份工作要花1,000美元&#xff1f; (Why does it cost $1,000 to list a job on Free Code Camp?) I’ve recently spoken with employers looking for JavaScript …

python訪問注冊表_讀取注冊表的Python代碼

如果“Uninstall”中有超過1024個子鍵怎么辦&#xff1f;Use _winreg.QueryInfoKey(key)Python2:import errno, os, _winregproc_arch os.environ[PROCESSOR_ARCHITECTURE].lower()proc_arch64 os.environ[PROCESSOR_ARCHITEW6432].lower()if proc_arch x86 and not proc_ar…

ios 動畫 隱藏tabbar_UITabBarViewController 的底部 tabBar 隱藏

iOS pushViewController 時候隱藏 TabBar 的可以用interfaceUIViewController (UINavigationControllerItem)property(nonatomic,readonly,strong)UINavigationItem*navigationItem;// Created on-demand so that a view controller may customize its navigation appearance.p…

JS進階之---函數,立即執行函數

一、函數 函數聲明、函數表達式、匿名函數 函數聲明&#xff1a;使用function關鍵字聲明一個函數&#xff0c;再指定一個函數名&#xff0c;叫函數聲明。function name () { … } 函數表達式&#xff1a;使用function關鍵字聲明一個函數&#xff0c;但未給函數命名&#xff0c;…

主線程中有多個handler的情況

https://www.cnblogs.com/transmuse/archive/2011/05/16/2048073.html轉載于:https://www.cnblogs.com/genggeng/p/9806415.html

RandomForestClassifier(隨機森林檢測每個特征的重要性及每個樣例屬于哪個類的概率)...

#In the next recipe, well look at how to tune the random forest classifier. #Lets start by importing datasets:from sklearn import datasets X, y datasets.make_classification(1000)# X(1000,20) #y(1000) 取值范圍【0,1】from sklearn.ensemble import RandomFores…

單因素方差分析_基于R語言開展方差分析(一)——單因素方差分析

基本原理方差分析(Analysis of variance, ANOVA)是用于兩個或兩個以上樣本均數比較的方法&#xff0c;還可以分析兩個或多個研究因素的交互交互作用以及回歸方程的線性假設檢驗等。其基本思想是將全部觀察值間的變異——總變異按設計和需要分解成兩個或多個組成部分&#xff0c…

個稅10% 人群_人群管理如何使我們的搜索質量提高27%

個稅10% 人群by Thanesh Sunthar由塔內什桑塔爾(Thanesh Sunthar) 人群管理如何使我們的搜索質量提高27&#xff05; (How Crowd Curation Improved Our Search Quality by 27%) The bigger your platform gets, the more vital search becomes. And if you run a content-hea…

mysql增數據語句_Mysql 數據增刪改查語句

插入數據 insert#1. 插入完整數據(順序插入)#語法一&#xff1a;insert into 表名(字段1,字段2,字段3…字段n) values (值1,值2,值3…值n);#語法二&#xff1a;insert into 表名 values (值1,值2,值3…值n);#2. 指定字段插入數據#語法&#xff1a;insert into 表名(字段1,字段2…