一、創建簡易Server
const http = require ( 'http' ) ;
const URL = require ( 'url' ) ; const HTTP_PORT = 8088 ; const server = http. createServer ( ( req, res ) => { const { headers, method, url } = req; console. log ( headers, method, url) ;
} ) ; server. listen ( HTTP_PORT , ( ) => { console. log ( ` 🚀 Outman 服務器已啟動,端口: ${ HTTP_PORT } ` ) ;
} )
二、url相關處理
const http = require ( 'http' ) ;
const URL = require ( 'url' ) ; const HTTP_PORT = 8088 ; const server = http. createServer ( ( req, res ) => { const { headers, method, url } = req; console. log ( headers, method, url) ; if ( url === '/login' ) { res. end ( 'hello outman' ) ; } else if ( url === '/products' ) { res. end ( 'products list' ) ; } else { res. end ( 'error request' ) ; } const parseInfo = URL . parse ( req. url) ; console. log ( parseInfo) ; const { pathname, query } = URL . parse ( req. url) ; const queryObj = URL . parse ( query) ; console. log ( pathname, queryObj) ;
} ) ; server. listen ( HTTP_PORT , ( ) => { console. log ( ` 🚀 Outman 服務器已啟動,端口: ${ HTTP_PORT } ` ) ;
} )
三、請求配置與監聽
const http = require ( 'http' ) ;
const URL = require ( 'url' ) ; const HTTP_PORT = 8088 ; const server = http. createServer ( ( req, res ) => { const { headers, method, url } = req; console. log ( headers, method, url) ; req. setEncoding ( 'utf-8' ) ; req. on ( 'data' , ( data ) => { console. log ( 'data' , data) ; const { username, password } = JSON . parse ( data) ; console. log ( username, password) ; } ) ; req. on ( 'end' , ( ) => { console. log ( '傳輸結束' ) ; } ) ; res. end ( 'outman msg' )
} ) ; server. listen ( HTTP_PORT , ( ) => { console. log ( ` 🚀 Outman 服務器已啟動,端口: ${ HTTP_PORT } ` ) ;
} )
四、常用HTTP CODE
HTTP狀態碼 狀態描述 信息說明 200 OK 請求成功 201 Created POST請求,創建新的資源 301 Moved Pemanently 請求資源的URL已經修改,響應中會給出新的URL 400 Bad Request 客戶端的錯誤,服務器無法或者不進行處理 401 Unauthorized 未授權的錯誤,必須攜帶請求的身份信息 403 Forbidden 客戶端沒有權限訪問,被拒接 404 Not Found 服務器找不到請求的資源 500 Internal Server Error 服務器遇到了不知道如何處理的情況 503 Service Unavailable 服務器不可用,可能處理維護或者重載狀態,暫時無法訪問