nodejs處理POST請求

2021-06-20 05:50:47 字數 1850 閱讀 6384

本節我們做乙個簡單的demo,post資料,並且接受資料

requesthandlers的模組

應用程式需要新的部件,因此加入新的模組 -- 已經無需為此感到新奇了。我們來建立乙個叫做requesthandlers的模組,並對於每乙個請求處理程式,新增乙個佔位用函式,隨後將這些函式作為模組的方法匯出:

requesthandlers的模組

start() : post表單html

upload : post資料獲取頁面

requesthandlers.js

function start(response, postdata) ); 

response.write(body); 

response.end(); 

}  function upload(response, postdata) ); 

response.write("you've sent: " + postdata); 

response.end(); 

}  exports.start = start; 

exports.upload = upload; 

router模組

通過檢查給定的路徑對應的請求處理程式是否存在,如果存在的話直接呼叫相應的函式,並返回相應是字串

router.js

function route(handle, pathname, response, postdata) else ); 

response.write("404 not found"); 

response.end(); 

}  } 

exports.route = route; 

server模組

處理請求模組

index模組

啟動模組,主模組

index.js

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

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

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

var handle = {} 

//區分大小寫的  

handle["/"] = requesthandlers.start; 

handle["/start"] = requesthandlers.start; 

handle["/upload"] = requesthandlers.upload; 

server.start(router.route, handle); 

執行後效果

如果現在啟動應用(node index.js,始終記得這個命令列),隨後請求乙個url,我請求的是http://localhost:8888/,然後顯示的是乙個form表單,輸入資料後提交表單後就會跳轉到http://localhost:8888/upload,你將會看到應用輸出相應的資訊,這表明我們的http伺服器已經在使用路由模組了,並會將請求的路徑傳遞給路由,路由再找到對應的處理函式:

nodejs獲取post請求和get請求的資料

nodejs對於post請求和get請求的獲取方式不一樣。1.get請求 用url模組處理req.url就能夠獲取get引數 var url require url params就是get方法攜帶的引數 var params url.parse req.url,true query 2.post請求...

nodejs路由 get和post請求

nodejs在路由這塊做得還是不錯的,經常接觸到的有get請求和post請求,我們知道nodejs是很難提供靜態服務的,如果用原生的nodejs的會比較麻煩,以下提供 介紹原生nodejs是怎樣處理get和post請求的post請求 node為了追求極致,它是乙個小段乙個小段接收的。接受了一小段,可...

nodejs處理get請求

主要記錄下獲取get請求裡面的引數的問題。假設有這樣乙個鏈結 urlstring hello?name lilei position general 要從這個鏈結裡提取出引數name和position的值。這裡要用到url模組和querystring模組,所以先準備這兩個物件。var url req...