【Nodejs】探索 Node.js、NPM和 Express

2023/08/29閱讀時間約 16 分鐘

這篇想來寫,剛碰到js得時候,為了讓程式可以運作而安裝Node.js 。Node.js 是能夠在伺服器上面運行 JavaScript 的應用平台環境,透過 Node.js 提供的函式庫與執行環境能完成伺服器端服務。此篇幅就直接從純後端的角度切入摟(對不起拉我寫來寫去還是不知道怎麼順順的寫好文章開頭QQ)

終端機運行指令為:

node app.js
  • 這邊給的代碼。當使用者瀏覽時(這邊因為是單機作業,就是127.0.0.1:3000),等同於對這個伺服器發送了一個請求,那終端機中會輸中請求的一些相關資訊:
// TODO:取得request資訊
const http = require("http");
const server = http.createServer((request, response) => {
console.log(response.url, response.method, response.headers);

});
server.listen(3000);
  • 取得請求後,伺服器會依據請求給予其回覆。以下示範,在伺服器被訪問時,發送出回覆的一種方式:

這邊的操作,在網頁被瀏覽時,會帶出HTML<p>node test</p>

// TODO:處理require
const http = require("http");
const server = http.createServer((request, response) => {
response.write('<html lang="en">');
response.write(
' <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head>'
);
response.write("<body><p>node test</p></body>");
response.write("</html>");
response.end();
});
server.listen(3000);

這邊的操作,在網頁被瀏覽時,會帶出button跟input

const http = require("http");
const server = http.createServer((request, response) => {
const url = request.url;
console.log(url);
response.write(
'<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head>'
);
response.write(
'<body><form method="get" action="/getMsg"><input type="text" name="msg" id="" /><input type="submit" value="submit" /></form></body>'
);
response.end();
});
server.listen(3000)



NPM(Node Package Manager)

接著我們要來談談,npm跟模塊(package)之間的關係:

在node中有三種模塊的方式:

  1. nodejs 自帶核心模塊 -> http, https, path, os
  2. 用戶自訂義模塊
  3. npm
raw-image

NPM 是 Node Package Manager 的簡稱,它是一個線上套件庫,可以下載各式各樣的 Javascript 套件來使用。

在以前呀,我們需要套件的時候,就得額外到套件的官網,下載,在裝到自己正在用的專案當中,哩哩摳摳,有時候再給你一個環境建置小紅自,直接讓你心態炸裂(這就是傳說中的寫程式入門到放棄嘛~)為了讓我們這些小菜雞不要還妹入門就直接放棄,世界上的大大們幫我們整理好套件,那我們只需要下指令,就一鍵安裝摟(天啊寫程式的人好暖,暈爛暈爛~)

但要記得,要先安裝nodejs才能使用歐!

npm安裝指令:

npm init
npm install

安裝成功的話,你就會看到你得專案多了這些三個檔案:

raw-image

有看到的話,在npm這一部分就安裝成功啦~

那接下來,介紹一個大家壹定會安裝的套件


nodemon

指令:npm install -g nodemon
啟動;nodemon 檔案

之前我們只要啟動終端機後,如果有更改裡面內容,就需要重啟終端機,再重新訪問,正在開發階段必須一直修修改改並且頻繁地測試內容,真的有點搞剛。

raw-image
nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

那如果有起動成功,就會出現下面著個畫面:

raw-image

Express

官網:https://expressjs.com

指令:npm i express

接下來介紹的express,先看GPT大大是如何解釋他:

Express 是一個流行的 Node.js Web 應用程序框架,它簡化了構建 Web 和 API 服務器的過程。它提供了一組強大的功能和工具,使開發者能夠更輕松地創建高性能、可擴展且易於維護的 Web 應用程序。

Express 提供了許多功能,包括:
1. 路由管理
2. 中間件(middleware)(可以在請求和響應之間執行一些操作)
3. RESTful API 構建
Express 提供了一個強大且靈活的框架,使得 Node.js 開發者能夠輕松構建各種類型的 Web 應用程序和服務。它是 Node.js 社區中最受歡迎和廣泛使用的 Web 框架之一。

總之,可以知道他是一個很棒棒的框架!那我們就來看看這個棒棒的框架如何使用吧。

// TODO: express 基本寫法
const express = require('express')
const app = express()

app.get('/', function (req, res) {
res.send('Hello World')
})

app.listen(3000)

這一段代碼中,我們可以得知兩件事:

在res中的res.write()跟res.end()在express中由res.send()取代

看到那個app.get(),他的名字叫middleware。


Middleware

那Middleware再請GPT大大開示:

Middleware(中間件)是在 Express 框架中用於處理請求和響應的函數。它可以訪問請求對象(`req`)、響應對象(`res`)以及應用程序中的下一個中間件函數(`next`)。中間件在請求處理過程中執行一些操作,然後可以決定是將請求傳遞給下一個中間件,還是結束請求-響應周期。

在 Express 中,中間件可以用來執行各種任務,例如:
1. 處理路由:根據不同的請求路徑,使用不同的中間件來處理不同的邏輯。
2. 記錄請求日志:記錄請求的信息,如請求時間、請求路徑、請求方法等。
3. 身份驗證和授權:驗證用戶身份,授權用戶訪問特定的資源。
4. 數據處理:解析請求體,處理表單數據、JSON 數據等。
5. 錯誤處理:捕獲和處理請求處理過程中的錯誤。

在 Express 中,中間件可以通過 `app.use()` 或類似的方法添加到應用程序中。例如,`app.use(middlewareFunction)` 將一個中間件函數添加到請求-響應處理管道中。多個中間件可以按順序添加,請求將依次通過每個中間件。

這裡可以大概知道,當伺服器運作時,middleware就承攬著伺服器要做的每一個動作。

app.use('/', function (req, res) {
res.send('Hello World')
})
raw-image

那這邊可以看到app後面可以接很多東西,其中的app.post(),app.get()分別接收POST跟GET的方法。














在express中使用get方法:

get方法搭配的是req.query()

// TODO: route -> 在表單中使用get
const express = require("express");
const http = require("http");

const app = express();

// 顯示表單
// form method="get" action="/result "
app.use("/add", (req, res, next) => {
res.send(
'<body><form method="get" action="/result"><input type="text" name="msg" id="" /><input type="submit" value="submit" /></form></body>'
);
next();
});

app.use("/result", (req, res, next) => {
console.log(req.query); //{ msg: 'qew' }
next();
});
app.use("/", (req, res, next) => {
res.send("<h1>this is root page. </h1>");
next();
});

const server = http.createServer(app);
server.listen(3000);


在express中使用post方法:

express本身並沒有提供使用post方法,所以要另外下載body-parser

下載指令 :$ npm install body-parser

post方法搭配的是req.body()

// TODO: route -> 在表單中使用post
// express本身不支援post,需要在額外使用bodyParser
const bodyParser = require("body-parser");
const express = require("express");
const http = require("http");
const adminRouters = require("./router/admin");
const shopRouters = require("./router/shop");
const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

router.use("/add", (req, res, next) => {
res.send(
'<body><form method="post" action="/result"><input type="text" name="msg" id="" /><input type="submit" value="submit" /></form></body>'
);
next();
});
router.use("/result", (req, res, next) => {
console.log(req.body); //{ msg: 'wer' }
res.send(req.body.title);
next();
});


router.use("/", (req, res, next) => {
res.send("<p>11111</p>");
res.send("<h1>this is root page. </h1>");
next();
});

// 404 not found
app.use((req, res, next) => {
res.status(404).send(<p>pages not found</p>);
});

const server = http.createServer(app);
server.listen(3000);

Express application generator

目前,加上【Nodejs】淺談網頁開發中的模板語言:Pug 和 EJS 這篇(還沒看的趕緊過去看XD),稍微都有提到基本的環計建置了。那接下來再提一個基於官方幫我們建置好的框架Express generator

raw-image

還是要先安裝Express generator拉~

指令:npm install -g express-generator

根據他給的提示下創建指令

raw-image

那像我的話,因為要使用的模板語言是ejs,所以指令為:

express -e express-generator-1

就等他幫你創建好摟~


🥰以上是本文所分享的內容。如果您發現任何錯誤或遺漏,請不吝賜教。







3會員
10內容數
留言0
查看全部
發表第一個留言支持創作者!