Node.js Server >>> Express

Node.js?

  • JavaScript 執行環境(run-time environment)
  • 讓 JavaScript 從瀏覽器解放

Node.js server

回傳 HTML >>> Content-Type >>> text/html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// include http module from Node.js
const http = require('http');

// define server related variables
const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
// HTTP status code
res.statusCode = 200;
// HTTP response Headers >>> content-type
res.setHeader('Content-Type', 'text/plain');
// HTTP response Body
res.end('This is my first server created in Node.js');
});

// start and listen the server
server.listen(port, hostname, () => {
console.log(`The server is listening on http://${hostname}:${port}`);
});

Express

  • JavaScript 後端框架

安裝方式

  • npm init / npm init -y
  • npm i express
1
2
3
4
5
6
7
8
9
10
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
res.send('This is my first Express.js app');
});
app.listen(port, () => {
console.log(`Express is running on http://localhost:${port}`);
});