搭建簡易express後臺服務
阿新 • • 發佈:2020-11-04
在搭建服務之前,確保電腦有node環境,如果沒有安裝node,則需要安裝node(可以搜尋node安裝教程),這裡提一下,node可以直接執行js檔案。
1. 安裝express
npm i express --save
當前express版本:"express":"^4.17.1"
2. 新建server.js檔案(此檔案作為服務檔案)
1 const express = require('express')
2 const app = express()
3 const port = 3000
4
5 app.get('/hello', function (req, res) {
6 res.end(`好好學習天天向上`)
7 })
8 app.listen(port, () => {
9 console.log(`demo is listening on port ${port}`)
10 })
3. 執行檔案:
node server.js
這裡需要簡單說一下
因為server.js檔案在根目錄下,所以可以直接使用命令node server.js執行檔案,即/server.js
如果server.js在根目錄檔案src資料夾下,則使用node src/server.js.
總結:使用node執行檔案,命令為 node + 檔案地址
執行結果:
PS E:\coding> node server.js
demo is listening on port 3000
這時,我們就開啟了3000服務埠
4. 簡單的寫一個index.html檔案請求3000請求(注意跨域問題)
1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <title>Document</title>
8 </head>
9
10 <body>
11 <script>
12 fetch('http://localhost:3000/hello').then(res => {
13 // return res.json()
14 return res.text()
15 }).then(res=>{
16 console.log(res)
17 })
18 </script>
19 </body>
20
21 </html>
直接運行當前的檔案,由於瀏覽器的同源策略,此時會報跨域的錯
此時我們可以利用express託管靜態檔案,然後訪問index.html(此時是與server.js在同一級資料夾下)
訪問當前檔案路徑:http://localhost:3000/index.html,開啟控制檯,即可看見請求的3000埠返回的結果:
到此,我們實現了一個簡易的express後臺服務