node創建一個簡單的web服務


本文將如何用node創建一個簡單的web服務,過程也很簡單呢~

開始之前要先安裝node.js

 

1.創建一個最簡單的服務

// server.js
const http = require('http')

http.createServer(function (request, response) {
  console.log('request come', request.url)
  
  response.end('132')
  
}).listen(8888)

 

函數接受request和response參數:

request:請求我們這個服務發送的內容都會被封裝在這個request對象里

response:服務返回內容就是對這個request對象進行操作。

response.end() 就是服務返回的內容,如果服務不返回內容,頁面就會報錯(一直處於加載中的狀態)

listen() 就是當前監聽的端口號啦

 

創建完js文件后,就要啟動服務了,打開命令行,輸入

node server.js // node 剛才創建的js名稱

在服務器中輸入 localhost:8888 就可以訪問我們這個服務了。

 

2.在server中讀取html

// server2.js
const http = require('http')
const fs = require('fs')

http.createServer((request, response)=> {
    console.log('request come', request.url)

    const html = fs.readFileSync('index.html', 'utf-8')
    response.writeHead(200, {
        'Content-Type': 'text/html'
    })

    response.end(html)
    
}).listen(8887)

console.log('listen at localhost:8887')
<!--index.html-->
<body>
    <p>server</p>
</body>

 

這時候在瀏覽器里輸入localhost:8888 就可以這個html了

 

簡單的創建服務已經完成啦。學到這里肯定覺得太簡單了。那么請看下面的部分。

1.前端跨域及其解決方案

2.前端需要了解的HTTP協議

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM