Thêm mã sau vào tệp websv01.js để tạo một HTTP server
const http = require('http');
// Tạo server
const server = http.createServer((req, res) => {
res.statusCode = 200; // Trả về mã trạng thái HTTP 200 (OK)
res.setHeader('Content-Type', 'text/plain'); // Định dạng dữ liệu trả về là text
res.end('Hello, this is my first Node.js server!');
});
// Lắng nghe kết nối trên cổng 3000
server.listen(3000, 'localhost', () => {
console.log('Server running at http://localhost:3000/');
});
node app.js
Truy cập vào http://localhost:3000/ trong trình duyệt, bạn sẽ thấy thông điệp:
Hello, this is my first Node.js server!
Node.js rất mạnh mẽ khi xây dựng web server. Bây giờ, hãy tạo một web server đơn giản sử dụng module http của Node.js.