如何用nodejs啟一個前端服務


1、新建文件夾,如 notice

2、新建頁面和js文件,如 index.html server.js

3、index.html頁面內容隨你寫,如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    你看到的這個頁面是首頁
</body>
</html>

4、關鍵的 server.js

var http=require('http'); //用來啟服務
var fs=require('fs'); //用來讀取文件
var root="C:/Users/Administrator/Desktop/notice" //你本地放index.html頁面的文件路徑

//
開啟服務 var server=http.createServer(function(req,res){ var url=req.url; var file = root+url; fs.readFile(file,function(err,data){ if(err){ res.writeHeader(404,{ 'content-type' : 'text/html;charset="utf-8"' }); res.write('<h1>404錯誤</h1><p>你要找的頁面不存在</p>'); res.end(); }else{ res.writeHeader(200,{ 'content-type' : 'text/html;charset="utf-8"' }); res.write(data);//將index.html顯示在客戶端 res.end(); } }) }).listen(8888); //端口號 console.log('服務器開啟成功');

5、輸入命令啟動服務: node server.js

6、出現下圖,說明服務啟動成功

7、打開瀏覽器,輸入ip+端口號/文件名即可打開文件,如 127.0.0.1:8888/index.html

8、如果還需新建文件,則新建的文件一定放在跟index.html同一目錄下,否則會檢索不到

 


免責聲明!

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



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