首頁  >  文章  >  web前端  >  nodejs搭建web網站

nodejs搭建web網站

WBOY
WBOY原創
2023-05-11 22:18:351781瀏覽

隨著網路技術的不斷發展,Node.js已成為人們廣泛使用的開發語言之一。 Node.js是一種基於Chrome V8引擎的JavaScript運行環境,適用於建立快速、可擴展的網路應用程式。在本文中,我們將介紹如何使用Node.js建立一個Web網站的過程。

一、環境搭建

在開始之前,需要先進行環境搭建。建議使用LTS版本的Node.js,在官網(https://nodejs.org/en/)下載對應系統的安裝包,並進行安裝。

安裝完成後,需確認Node.js的環境變數是否配置成功。打開命令列窗口,輸入node -v,如果出現版本號,證明安裝成功。

二、搭建HTTP伺服器

Node.js提供了http模組,可以透過這個模組建立一個Web伺服器。其中,createServer()方法建立HTTP伺服器,listen()方法監聽指定的連接埠和IP位址。

程式碼如下:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World!
');
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

以上程式碼建立了一個簡單的HTTP伺服器,監聽本機3000埠。在瀏覽器中輸入http://127.0.0.1:3000/,即可存取該伺服器上的頁面。頁面內容為Hello World!。

三、處理路由

如果只是簡單的傳送Hello World給客戶端!訊息,那麼使用HTTP伺服器就已經足夠了。但是在實際開發中,會遇到更複雜的請求回應場景,需要處理路由。

本例中,假設有兩個頁面:/home 和/about。當請求存取這兩個頁面時,需要進行不同的處理。因此,可以在HTTP伺服器中新增路由處理。

程式碼如下:

const http = require('http');
const url = require('url');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    const uri = url.parse(req.url).pathname;
    if (uri === '/home') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Welcome to the homepage!
');
    } else if (uri === '/about') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('About the website!
');
    } else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/plain');
        res.end('404 Not Found
');
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

以上程式碼中,使用了Node.js內建的url模組,將請求的url位址解析為pathname,用於路由處理。當請求的pathname為/home時,伺服器傳回「Welcome to the homepage!」;當請求的pathname為/about時,伺服器傳回「About the website!」;當請求的pathname不存在時,伺服器傳回404 Not Found 。

四、使用模板引擎

在實際開發過程中,使用模板引擎可以大幅提升開發效率。常用的模板引擎有ejs、handlebars、jade等。本例中,使用ejs模板引擎進行頁面渲染。

首先,透過npm安裝ejs模組:

npm install ejs --save

在HTTP伺服器中進行修改,使用範本引擎渲染HTML頁面:

const http = require('http');
const url = require('url');
const ejs = require('ejs');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    const uri = url.parse(req.url).pathname;

    if (uri === '/home') {
        fs.readFile('./views/home.ejs', 'utf8', (err, data) => {
            if (err) {
                console.log(err);
                res.statusCode = 404;
                res.setHeader('Content-Type', 'text/plain');
                res.end('File not found!
');
            } else {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/html');
                const template = ejs.compile(data);
                const html = template({title: 'Home Page', message: 'Welcome to the homepage!'});
                res.end(html);
            }
        });
    } else if (uri === '/about') {
        fs.readFile('./views/about.ejs', 'utf8', (err, data) => {
            if (err) {
                console.log(err);
                res.statusCode = 404;
                res.setHeader('Content-Type', 'text/plain');
                res.end('File not found!
');
            } else {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/html');
                const template = ejs.compile(data);
                const html = template({title: 'About Page', message: 'About the website!'});
                res.end(html);
            }
        });
    } else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/plain');
        res.end('404 Not Found
');
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

以上程式碼中,使用了fs模組讀取模板文件,使用ejs模組渲染模板文件,將產生的HTML頁面傳回給客戶端。

五、使用靜態文件

在實際開發中,通常會使用到靜態文件,如圖片、CSS文件、JavaScript文件等。 Node.js提供了靜態檔案服務,可以用來處理靜態檔案的請求。

程式碼如下:

const http = require('http');
const url = require('url');
const ejs = require('ejs');
const fs = require('fs');
const path = require('path');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    const uri = url.parse(req.url).pathname;
    const filename = path.join(process.cwd(), uri);

    fs.exists(filename, (exists) => {
        if (!exists) {
            res.statusCode = 404;
            res.setHeader('Content-Type', 'text/plain');
            res.end('404 Not Found
');
            return;
        }

        if (fs.statSync(filename).isDirectory()) {
            filename += '/index.html';
        }

        fs.readFile(filename, 'binary', (err, file) => {
            if (err) {
                res.statusCode = 500;
                res.setHeader('Content-Type', 'text/plain');
                res.end(err + '
');
                return;
            }

            res.statusCode = 200;
            const extname = path.extname(filename);
            res.setHeader('Content-Type', mimeTypes[extname] || 'text/plain');
            res.write(file, 'binary');
            res.end();
        });
    });
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

以上程式碼中,使用fs模組判斷請求的檔案是否存在,使用path模組處理路徑,使用mimeTypes定義檔案類型。如果請求的檔案不存在,則傳回404 Not Found;如果請求的是資料夾,則預設請求資料夾中的index.html檔案;如果檔案讀取成功,則傳回200,同時設定Content-Type頭和回應體。

透過以上的操作,我們就成功地使用Node.js搭建了一個Web網站,實現了基本的路由處理和靜態檔案服務。透過更進一步的學習和實踐,我們可以做出更複雜的Web網站,並實現更多的功能,例如資料庫操作、請求代理等。

以上是nodejs搭建web網站的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn