Xây dựng ứng dụng web
Xây dựng ứng dụng web
- Tạo đường dẫn mới.
mkdir my_webapp
cd my_webapp
- Sau đó khởi tạo dự án Node.js.
Tạo ứng dụng Express
- Tải Express.
- Sau khi chạy dòng lệnh này, bạn sẽ thấy dependency xuất hiện trong tệp package.json. Thêm vào đó, tập tin node_modules và tệp package-lock.json được tạo.

- Tạo tệp mới tên app.js.
- Chọn tệp app.js và dán đoạn code này. Sau đó lưu.
var express = require('express');
var app = express();
var fs = require('fs');
var port = 8080;
app.listen(port, function() {
console.log('Server running at http://127.0.0.1:', port);
});

Tạo một REST API
- Thêm đoạn code dưới đây vào tệp
app.js
.
var express = require('express');
var app = express();
var fs = require('fs');
var port = 8080;
/*global html*/
// New code
app.get('/test', function (req, res) {
res.send('the REST endpoint test run!');
});
app.get('/', function (req, res) {
html = fs.readFileSync('index.html');
res.writeHead(200);
res.write(html);
res.end();
});
app.listen(port, function() {
console.log('Server running at http://127.0.0.1:%s', port);
});
Xây dựng nội dung HTML
- Tạo tệp tên index.html.
- Chọn tệp index.html. Sau đó dán đoạn code bên dưới vào và lưu.
<html>
<head>
<title>Elastic Beanstalk App</title>
</head>
<body>
<h1>Welcome to the FCJ Workshop</h1>
<a href="/test">Call the test API</a>
</body>
</html>

Chạy thử đoạn code
- Chọn tệp package.json.
- Thay đổi nội dung tệp package.json và lưu.
"scripts": {
"start": "node app.js"
},

- Tại terminal, chạy lệnh.
- Đi đến đường dẫn xuất hiện để thấy kết quả.
