สร้างเว็บเซอร์เวอร์ด้วย Express

สร้างโฟลเดอร์ให้แอพชื่อ myapp

mkdir myapp
cd myapp

ใช้คำสั่ง npm init เพื่อสร้างไฟล์ package.json

> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (myapp)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\Project\node\myapp\package.json:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) y

จะได้ไฟล์ package.json

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

ติดตั้ง express ให้กับโปรเจ็กส์นี้

npm install express --save

ไฟล์ package.json จะเพิ่ม dependencies

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

สร้างไฟล์ server.js

var express = require('express')
var app = express()
 
app.get('/', function (req, res) {
    res.send('Hello World')
})
 
app.listen(3000)
console.log("Server running at port 3000");

หรือ

const express = require('express')
const app = express()
const port = 3000
 
app.get('/', (req, res) => res.send('Hello World!'))
 
app.listen(port, () => console.log(`App listening on port ${port}!`))

ทดลองรัน

> node server.js
Server running at port 3000

เปิด browser ไปที่ http://localhost:3000/
จะเห็นข้อความ Hello World