快速搭建本地服務
阿新 • • 發佈:2020-11-22
方式一:
安裝下載serve
npm包。https://www.npmjs.com/package/serve
npm i serve
# 建議全域性安裝,
npm i -g serve
安裝完成你可以serve -v
來檢視版本號,至此安裝成功了,
serve -v
WARNING: Checking for updates failed (use `--debug` to see full error)
11.3.2
直接在開啟你的檔案目錄,執行serve
就會直接啟動一個服務,預設監聽 5000
埠
服務的啟動的方式,還可以在
serve fileName
後面跟資料夾的名稱,以此來作為服務啟動的檔案目錄。
serve WARNING: Checking for updates failed (use `--debug` to see full error) ┌───────────────────────────────────────────────────┐ │ │ │ Serving! │ │ │ │ - Local: http://localhost:5000 │ │ - On Your Network: http://192.168.137.1:5000 │ │ │ │ Copied local address to clipboard! │ │ │ └───────────────────────────────────────────────────┘
恭喜你服務搭建完成!
方式二;
使用node的http
內建模組來快速的新建一個服務,
此操作代表你已經安裝了
nodejs
不然將不可用。
// 引入http包 const http = require('http') const app = new http.Server() // 偵聽請求 app.on('request', (req, res) => { res.writeHead(200, { "Content-Type": 'text/html;charset=UTF-8', }) // 返回響應內容 res.write('<h1>Node.js-監聽3000埠~</h1>') // 結束響應,此方法必須呼叫,不然客戶端會一直處於等待狀態。 res.end() }) // 監聽 3000埠 app.listen(3000, (err) => { if (!err) { console.log('開始監聽3000埠') } })
shell中啟動這個檔案,node fileName
node service
開始監聽3000埠
方式三;
下載安裝依賴express
,點選下載
npm i express
引入並建立服務
// 引入包 express
const express = require('express')
// 建立伺服器;
const app = express()
// 建立get請求
app.get('/', (req, res) => {
res.send('請求成功')
})
// 啟動服務;
app.listen(3000, (err) => {
if (!err) {
console.log('server started on port 3000')
}
})
// ============
node service.js
server started on port 3000