Xây dựng ứng dụng web

Xây dựng ứng dụng web

  1. Tạo đường dẫn mới.
mkdir my_webapp
cd my_webapp
  1. Sau đó khởi tạo dự án Node.js.
npm init -y

Tạo ứng dụng Express

  1. Tải Express.
npm install express
  1. 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.

Build application

  1. Tạo tệp mới tên app.js.
touch app.js
  1. 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);
});

Build application

Tạo một REST API

  1. 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

  1. Tạo tệp tên index.html.
touch index.html
  1. 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>

Build application

Chạy thử đoạn code

  1. Chọn tệp package.json.
  2. Thay đổi nội dung tệp package.json và lưu.
"scripts": {
    "start": "node app.js"
},

Build application

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

Build application