nodejs模組 http模組

2021-09-23 19:35:52 字數 2311 閱讀 1711

//

處理url請求

var fs = require('fs');

主頁function

home(res) );

res.write(content);

res.end();}//

about.html 關於頁面

function

about(res) );

res.write(content);

res.end();}//

匯出頁面處理函式

exports.home =home;

exports.about = about;

上面是建立http server,判斷url,處理url。

現在寫主程式來執行http server,**如下:

//

主程式//

引入server,router及requesthandler

var server = require('./server');

var router = require('./router');

var requesthandlers = require('./requesthandlers');

//儲存url處理方法

var handle ={};

handle['/'] =requesthandlers.home;

handle['/about'] =requesthandlers.about;

//啟動http server

server.start(router.route, handle);

至此,所有伺服器**寫完。

home.html

doctype html

>

<

html

>

<

head

>

<

meta

charset

="utf-8"

>

<

title

>home page

title

>

head

>

<

body

>

<

p>home page

p>

body

>

html

>

about.html

doctype html

>

<

html

>

<

head

>

<

meta

charset

="utf-8"

>

<

title

>about page

title

>

head

>

<

body

>

<

p>about page

p>

body

>

html

>

404.html

doctype html

>

<

html

>

<

head

>

<

meta

charset

="utf-8"

>

<

title

>404 page

title

>

head

>

<

body

>

<

p>404 page not found

p>

body

>

html

>

$ node main.js
訪問會看到home page頁面。

訪問/about顯示about page頁面。

其他顯示404 page 頁面。

出現這種錯誤一般就是已經執行的另乙個伺服器使用了相同的埠,換乙個埠就可以了。

NodeJS初識 http模組

get的資訊在位址列,不需要設定請求頭資訊 post的資訊在請求體,需要設定請求頭資訊ajax步驟 寫請求頭資訊 訪問位址 傳輸資料 訪問方式http協議 1.建立伺服器 2.req傳送請求體 傳送方式,訪問位址,是否非同步 是否設定請求頭資訊 是否向伺服器傳送資料 post才傳送資料 狀態事件暫時...

nodejs自帶http模組學習

node.js 入門教程 預設啟動埠是3000 根據檔案型別,瀏覽器正確處理資料 如果獲取不到檔案,則返回400錯誤,並跳轉到404.html 如果是進入 根目錄,則進入 public index.html檔案 nodejs檔案只讀取一次 server.js 檔案的啟動檔案 進入 404 介面 fu...

nodejs核心模組之http

http模組包含以下5個核心類和方法及屬性 核心類 2.http.createserver 該方法返回http.server類的例項,該例項繼承了eventemitter 類。eventemitter 類有乙個特殊的事件error,當連線失敗的時候會自動觸發該error事件,因此在建立http伺服器...