伺服器端的介紹

翻譯不完整。 請幫助我們翻譯這篇文章!

歡迎來到MDN伺服器端的程式初學者課程 ! 在第一篇文章中,我們會專注在伺服器端的高階程式,並回答"這是什麼?","這個和用戶端的程式有什麼區別?",和"為什麼這個有用?" 。在閱讀完這篇文章後,你將會得到額外的知識得以編寫伺服器端的程式。

先決條件: 基本電腦讀寫能力、對網路伺服器有基本了解。
目標: 熟悉何謂伺服器端的程式、它可以做什麼、它和用戶端的程式有什麼不一樣?

大部分的大型網站使用伺服器端程式碼(server-side code)來動態顯示各種所需的資料,普遍做法為撈取伺服端資料庫的資料,並將之送至用戶端以程式碼實作顯示方式(例如:HTML與JavaScript)。

對於伺服器端程式碼最大的效益也許就是針對個人用戶調製網頁內容。動態網站可以強調與使用者偏好及興趣更為相關的內容,也可以儲存個人設定及資訊讓網站更易於使用 — 例如重複使用已儲存的信用卡資料來使交易流程更為順暢。

它甚至允許網站使用者之間經由信件或其他管道,發送提示與更新進行互動。所有的這些網站功能讓其與用戶進行更深入的互動。

何謂伺服器端網站程式開發?

網頁瀏覽器使用超文本傳輸協定(HyperText Transfer Protocol, HTTP)與網頁伺服器(web servers)溝通。當您點選一個網頁上的連結、送出一份表單,或者執行搜尋,一段HTTP請求request)會由您的瀏覽器送出至目標伺服器。

該請求(request)包含一個用來指定受影響資源的URL、一個定義行為的請求方法(例如對資源進行get、delete或post)與當進行HTTP POST方法時可能包含編碼於URL參數中的額外資訊(經由一段查詢字串送出的各個鍵值對),或是在關聯的cookies中。

網頁伺服器等待用戶端的請求訊息、獲得後處理它們,並以一個HTTP回應response)訊息回覆至網頁瀏覽器。該回應包含一個狀態訊息說明本次請求是否達成(例如:"HTTP/1.1 200 OK"表示成功)。

成功對應於一個請求的回應主體(response body)應包含請求的資源(例如:一份新的HTML頁面或一張圖片等),這些可能將被用來顯示在網頁瀏覽器中。

靜態網站

以下的靜態網站(static site)圖展示一個基本的網頁伺服器架構,其中靜態網站意謂當無論何時有個特定資源的請求,伺服器始終回傳相同的硬編碼內容(hard-coded content)。當一個使用者想要引導到一個網頁時,瀏覽器送出的HTTP "GET" 請求指的就是該資源的URL。

此伺服器從它的檔案系統取回被請求的文件,並回傳一個包含此文件以及成功狀態碼(通常為200 OK)的HTTP回應。若檔案因某些原因無法被取回,則回傳一個錯誤狀態(參見 用戶端錯誤回應 與 伺服器端錯誤回應)。

A simplified diagram of a static web server.

動態網站

一個動態網站的回應內容是當需要時動態產生的。在一個動態網站的HTML網頁通常是經由資料庫取得並插入資料至HTML範本的佔位符(placeholders)中而創造出來(相較於靜態網站,這對於儲存大量內容而言,這是一種相當有效率的做法)。 

一個動態網站可以根據使用者或已存偏好設定提供的URL資訊回傳不同的資料,也可以以其他的作用方式呈現回應(例如:發送通知)。

用來支援一個動態網站的大部分的程式碼必須在伺服器執行。建立程式碼的方式稱為"伺服端程式設計(server-side programming)"或"後端腳本(back-end scripting)"。

下圖為動態網站dynamic website)的基本架構。如同先前的圖說,瀏覽器發送HTTP請求至伺服器,接著伺服器處理請求後,回傳合適的HTTP回應。

對於靜態資源的請求處理方式如同靜態網站的方式(靜態資源為任何不會改變的檔案 — 通常為CSS、JavaScript、圖片、預產生的PDF檔案等)。 

A simplified diagram of a web server that uses server-side programming to get information from a database and construct HTML from templates. This is the same diagram as is in the Client-Server overview.

對於動態資源的請求方式則為轉送(2)至伺服端程式碼(如圖中的網頁應用程式 Web Application)。對於"動態請求",伺服器解釋該請求、從資料庫讀取所需資訊(3)、與HTML範本結合取得的資料(4),最後送回一個包含已產生HTML的回應(5,6)。

伺服端與用戶端程式設計是相同的嗎?

讓我們把注意力集中在伺服端與用戶端的程式設計吧!在以下的每個案例中,程式碼完全不一樣:

  • 他們有不同的目的與考量。
  • 一般而言,他們不使用相同的程式語言(除了JavaScript可以使用在伺服端與用戶端以外)。
  • 他們在不同的作業系統環境下執行。

執行在瀏覽器的程式碼被稱為用戶端程式碼client-side code),它主要用來改善一個渲染的網頁外觀與行為。這包含選取與設定UI元件樣式、建立佈局、導覽、表格驗證等。相對的,伺服端網站程式設計大量涉及要回傳哪些內容給瀏覽器做為對請求的回應。伺服端程式碼處理驗證已提交的資料與請求、使用資料庫儲存及取得資料,和按需求發送正確的資料給用戶等任務。

用戶端程式碼以HTMLCSSJavaScript撰寫 — 它執行在網頁瀏覽器內,並且僅有或無訪問底層的作業系統(包含對檔案系統的有限存取)。

網頁開發者不能控制使用者可能使用何種瀏覽器來檢視一個網站 — 瀏覽器與用戶端程式有著不同層度的相容性,並且用戶端程式的挑戰之一是如何妥善地處理瀏覽器支援的差異。

伺服端程式碼可以為任何程式語言 — 例如有名的伺服端網頁語言包括PHP、Python、Ruby、C#與NodeJS(JavaScript)。該伺服端程式碼擁有完整的作業系統存取權限,而且開發者能夠選擇他們想要的程式語言(以及特定版本)。

開發者們通常使用網頁框架web frameworks)撰寫程式碼。網頁框架為功能函式、物件、規則與其他程式碼的集合,旨在解決常見問題、加速開發並簡化在特定域中面臨到的不同類型的任務。

再者,儘管用戶端與伺服端程式碼都使用框架,但會因為非常不同的域,而使得框架也不同。用戶端網頁框架簡化佈局與呈現的任務,而伺服端網頁框架則提供大量"通用"的網頁伺服器功能,否則你可能必須要自己實現(例如:對sessions的支援、對使用者認證的支援、簡易資料庫存取、樣板庫等)。

Note: Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple web site UI.

In contrast, you would almost never consider writing the server-side component of a web app without a framework — implementing a vital feature like an HTTP server is really hard to do from scratch in say Python, but Python web frameworks like Django provide one out of the box, along with other very useful tools.

在伺服端,你能做什麼?

伺服端程式設計是非常有用的,因為它讓我們有效地遞送替單個使用者量身訂做的資訊,從而創造更棒的使用者體驗。

如Amazon這樣的公司使用伺服端程式設計來建構產品搜尋結果、根據顧客偏好與過往購物習慣提供針對性的產品建議、簡化購物過程等。

銀行使用伺服端程式設計來儲存帳號資訊,並讓已授權用戶檢視與進行交易。其他服務如Facebook、Twitter、Instagram與Wikipedia使用伺服端程式設計來突顯、分享與控制使用者存取到感興趣的內容。

一些常見的伺服端程式設計使用案例與效益列舉如下。您將會注意到這當中會有些重疊的部分!

高效率資訊儲存與遞送

想像一下,在Amazon可以找到多少產品,或者說在Facebook上有多少文章?對各個產品或文章建立各別的靜態網頁完全是不切實際的。

伺服端程式設計反而是可以讓我們將資訊儲存至資料庫,並且動態建構及回傳HTML與其他型態的檔案(例如:PDF、圖片等)。它也可以藉由合適的用戶端網頁框架(利用這個方式可以降低在伺服器的處理負擔,亦減少需要被送出的大量資料)僅回傳資料(JSONXML等)來進行畫面渲染。

伺服器並不侷限於從資料庫發送資訊,還可以回傳軟體工具的結果或是來自通訊服務的資料。這些內容甚至可以針對到收到它的用戶裝置類型。

由於資訊存在於資料庫中,它可以輕易地與其他商業系統進行分享與更新(例如:當產品在線上或在店家中售完,店家可能會更新該產品的庫存資料庫)。

Note: Your imagination doesn't have to work hard to see the benefit of server-side code for efficient storage and delivery of information:

  1. Go to Amazon or some other e-commerce site.
  2. Search for a number of keywords and note how the page structure doesn't change, even though the results do. 
  3. Open two or three different products. Note again how they have a common structure and layout, but the content for different products has been pulled from the database.

For a common search term ("fish", say) you can see literally millions of returned values. Using a database allows these to be stored and shared efficiently, and it allows the presentation of the information to be controlled in just one place.

Customised user experience

Servers can store and use information about clients to provide a convenient and tailored user experience. For example, many sites store credit cards so that details don't have to be entered again. Sites like Google Maps can use saved or current locations for providing routing information, and search or travel history to highlight local businesses in search results.

A deeper analysis of user habits can be used to anticipate their interests and further customize responses and notifications, for example providing a list of previously visited or popular locations you may want to look at on a map.

Note: Google Maps saves your search and visit history. Frequently visited or frequently searched locations are highlighted more than others.

Google search results are optimized based on previous searches.

  1.  Go to Google search.
  2.  Search for "football".
  3.  Now try typing "favourite" in the search box and observe the autocomplete search predictions.

Coincidence? Nada!

Controlled access to content

Server-side programming allows sites to restrict access to authorized users and serve only the information that a user is permitted to see.

Real world examples include:

  • Social networks like Facebook allow users to fully control their own data but only allow their friends to view or comment on it. The user determines who can see their data, and by extension, whose data appears in their feed —  authorization is a central part of the user experience!
  • The site you are on right now controls access to content: articles are visible to everyone, but only users who have logged in can edit the content. To try this, click on the Edit button at the top of this page — if you are logged in you will be shown the edit view; if you are not logged in you will be taken to the sign-up page.

Note: Consider other real examples where access to content is controlled. For example, what can you see if you go to the online site for your bank? Log in to your account — what additional information can you see and modify? What information can you see that only the bank can change?

Store session/state information

Server-side programming allows developers to make use of sessions — basically, a mechanism that allows a server to store information on the current user of a site and send different responses based on that information.

This allows, for example, a site to know that a user has previously logged in and display links to their emails or order history, or perhaps save the state of a simple game so that the user can go to a site again and carry on where they left it.

Note: Visit a newspaper site that has a subscription model and open a bunch of tabs (e.g. The Age). Continue to visit the site over a few hours/days. Eventually, you will start to be redirected to pages explaining how to subscribe, and you will be unable to access articles. This information is an example of session information stored in cookies.

Notifications and communication

Servers can send general or user-specific notifications through the website itself or via email, SMS, instant messaging, video conversations, or other communications services.

A few examples include:

  • Facebook and Twitter send emails and SMS messages to notify you of new communications.
  • Amazon regularly sends product e-mails that suggest products similar to those already bought or viewed that you might be interested in.
  • A web server might send warning messages to site administrators alerting them to low memory on the server, or suspicious user activity.

Note: The most common type of notification is a "confirmation of registration". Pick almost any large site that you are interested in (Google, Amazon, Instagram, etc.) and create a new account using your email address. You will shortly receive an email confirming your registration, or requiring acknowledgment to activate your account.

Data analysis

A website may collect a lot of data about users: what they search for, what they buy, what they recommend, how long they stay on each page. Server-side programming can be used to refine responses based on analysis of this data.

For example, Amazon and Google both advertise products based on previous searches (and purchases).

Note: If you're a Facebook user, go to your main feed and look at the stream of posts. Note how some of the posts are out of numerical order - in particular, posts with more "likes" are often higher on the list than more recent posts.

Also look at what kind of ads you are being shown — you might see ads for things you looked at on other sites. Facebook's algorithm for highlighting content and advertising can be a bit of a mystery, but it is clear that it does depend on your likes and viewing habits!

Summary

Congratulations, you've reached the end of the first article about server-side programming. 

You've now learned that server-side code is run on a web server and that its main role is to control what information is sent to the user (while client-side code mainly handles the structure and presentation of that data to the user).

You should also understand that it is useful because it allows us to create websites that efficiently deliver information tailored for individual users and have a good idea of some of the things you might be able to do when you're a server-side programmer.

Lastly, you should understand that server-side code can be written in a number of programming languages and that you should use a web framework to make the whole process easier. 

In a future article we'll help you choose the best web framework for your first site; Next, though we'll take you through the main client-server interactions in just a little more detail.

In this module