創建新的服務器
創建一個簡單的服務
var http = require("http"); var server = http.createServer(); server.listen(8888);
這段代碼只會啟動一個偵聽8888端口的服務器,不會應答,不會任何事,所以是無意義的。
下面創建一個有意義的服務器
var http = require("http"); http.createServer(function(request, response) { console.log('get request'); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
結果:
//服務端 $ node http.js get request
//客戶端 $ curl localhost:8888 Hello World
這里我們通過response.writeHead發送一個請求狀態碼和內容類型,使用 response.write() 函數在HTTP響應主體中發送文本“Hello World"。
response.end()這個方法告訴服務器,所有的響應頭和響應體已經發送,服務器可以認為消息結束。
在curl下測試不出我們請求兩次的問題,我們在瀏覽器端輸入:http://localhost:8888/
Request Pathname Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: '/', path: '/', href: '/' } Request Pathname Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: '/favicon.ico', path: '/favicon.ico', href: '/favicon.ico' }
發現請求了兩次。
注意:當我們在服務器訪問網頁時,我們的服務器可能會輸出兩次“get request”。那是因為大部分瀏覽器都會在你訪問 http://localhost:8888/時嘗試讀取 http://localhost:8888/favicon.ico )
解析請求路徑
這時候我們需要另外一個模塊,url
var http = require("http"); var url = require("url") http.createServer(function(request, response) { var pathname = url.parse(request.url).pathname; console.log('Request Pathname ',pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
發送請求:localhost:8888/demo/test
curl localhost:8888/demo/test
查看解析的url結果:
Request Pathname /demo/test
我們取到瀏覽請求的url,這個可以幫助我們做路由映射。
url.parse很神奇,那我們再來多了解一點。
將原來的代碼處url.parse修改一下
pathname = url.parse(request.url)
發送請求:http://localhost:8888/select?page=10&blog=nodejs
Url {
protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?page=10&blog=nodejs', query: 'page=10&blog=nodejs', pathname: '/select', path: '/select?page=10&blog=nodejs', href: '/select?page=10&blog=nodejs' }
這就是整個解析后的url。
解析請求參數
使用querystringnodejs自帶的模塊解析參數
修改一下代碼:
var http = require("http"); var url = require("url"); var querystring = require('querystring') http.createServer(function(request, response) { var pathname = url.parse(request.url); var query = querystring.parse(pathname.query); console.log('query ',query); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);
query { page: '10', blog: 'nodejs' }
querystring.parse()有點類似於JSON.parse()
querystring.stringify()有點類似於JSON.stringify()
查看有querystring 哪些方法:
> var querystring = require('querystring') undefined > querystring { unescapeBuffer: [Function], unescape: [Function], escape: [Function], encode: [Function], stringify: [Function], decode: [Function], parse: [Function] }
發送post請求
這個例子有點復雜。
我們先創建一個服務器localhost:8000,然后通過自定義路由來處理請求。這里我們還是用http.request()發送了一個到localhost:8000/test的請求,並嘗試獲取post的數據。
var http = require("http"); var url = require("url"); var querystring = require('querystring') http.createServer(function(request, response) { var pathname = url.parse(request.url); var query = querystring.parse(pathname.query); if (pathname.pathname === '/getDo') { //處理localhost:8000/getDo response.writeHead(200, { "Content-Type": "text/plain" }); response.write("Hello World"); response.end(); } else if (pathname.pathname === '/postDo') { //處理localhost:8000/postDo postTest(response); } else if (pathname.pathname === '/test') { var jsonData = ''; request.on("data", function(data) { jsonData += data console.log('接受數據中。。。'); }); request.on("end", function() { console.log('接受完成!'); console.log(querystring.parse(jsonData)); }) } }).listen(8888); function postTest(response) { var postData = querystring.stringify({ 'msg': 'Hello World!' }) //發送post請求localhost:8000/test並帶上參數postData var options = { hostname: 'localhost', port: 8888, path: '/test', method: 'POST', headers: { 'Content-Type': '"text/plain', 'Content-Length': postData.length } }; var req = http.request(options); req.write(postData); req.end() }
接受數據中。。。
接受完成!
{ msg: 'Hello World!' }
這里我們通過請求localhost:8000/postDo的時候,又通過http發送了localhost:8000/test這個請求,並通過req.write(postData)帶上了post的參數。
應該這里沒有使用任何框架,post的數據必須通過
var jsonData = ''; request.on("data", function(data) { jsonData += data console.log('接受數據中。。。'); }); request.on("end", function() { console.log('接受完成!'); console.log(querystring.parse(jsonData)); })
這樣的形式來拼接。