//監聽 Client Close 事件之處理 myConnect.on('close', function (had_error) { if (had_error) console.log('連線錯誤'); elseconsole.log('Client 連線已關閉,伺服器持續運作中。..'); }); });
//啟用 Server 服務 const host = '192.168.1.105'; const port = 3999; server.listen(port, host, function () { console.log(`伺服器服務中。...${host}:${port}`); });
let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); // at this point, `body` has the entire request body stored in it as a string });
http.createServer((request, response) => { const { headers, method, url } = request; let body = []; request.on('error', (err) => { console.error(err); }).on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); // At this point, we have the headers, method, url and body, and can now // do whatever we need to in order to respond to this request. }); }).listen(8080); // Activates this server, listening on port 8080.
response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); // Note: the 2 lines above could be replaced with this next one: // response.writeHead(200, {'Content-Type': 'application/json'})
const responseBody = { headers, method, url, body };
response.write(JSON.stringify(responseBody)); response.end(); // Note: the 2 lines above could be replaced with this next one: // response.end(JSON.stringify(responseBody))
//對伺服器進行開機並於完成作業後顯示文字至終端機 const hostname = '127.0.0.1', port = 3000; //設定 Web 主機與通訊埠 server.listen(port, hostname, () => { console.log(` Server running at http://${hostname}:${port}/ Close Server press 'Ctrl+C' to exit `); });
接著終端機輸入指令。透過提示的指令開啟瀏覽器至指定 URL 網頁得到提示與伺服器運作之真實網頁。
1 2 3 4
L:\nodeTest>node webServerTXT.js
Server running at http://127.0.0.1:3000/ Close Server Use Key 'Ctrl+C'
fs.readFile(result.filePath, function (err, content) { response.writeHead(result.code, { 'Content-Type': 'text/html' }); //設定 response HEAD if (!err) response.end(content); else response.end(pageDir + 'page404.html'); //如果檔案讀取失敗直接顯示 404 檔案 });
}).listen(3333, "127.0.0.1", () => { console.log(`Server running!! try http://127.0.0.1:3333/apple show 'word A' try http://127.0.0.1:3333/banana show 'word B' try http://127.0.0.1:3333/cat show '404 ERROR' `); });