ExpressJS là 1 framework phổ biến của NodeJS

Yêu cầu máy đã cài NodeJSnpm

Gọi lệnh: npm install express trong cửa sổ terminal của Node để cài module Express

expressjs_post1_1

Tạo 1 file script (mình đặt tên là HelloWorld.js) để test với nội dung

var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function(req, res){
res.type('text/plain');
res.send('Hello TranKyPhat.com');
});
app.get('/about', function(req, res){
res.type('text/plain');
res.send('About my site');
});
// custom 404 page
app.use(function(req, res){
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});
// custom 500 page
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
app.listen(app.get('port'), function(){
console.log( 'Express started on http://localhost:' +
app.get('port') + '; press Ctrl-C to terminate.' );
});

Sau đó gọi lệnh chạy node HelloWorld.js

expressjs_post1_2

Kết quả:

expressjs_post1_3

 

Hello World ExpressJS 4.x

Category: Uncategorized
0
4236 views

Join the discussion

Your email address will not be published. Required fields are marked *