利用express開(kāi)啟服務(wù)
新建文件夾,包含app.js 與index.html
項(xiàng)目結(jié)構(gòu)

image.png
app.js代碼
const express = require('express');
const fs=require("fs");
const app = express();
app.use(express.static("public"));
// 使用fs.readFile打開(kāi)html文件
app.get("/hello.html", function(request, response) {
fs.readFile("./"+request.path.substr(1),function(err,data){
// body
if(err){
console.log(err);
//404:NOT FOUND
response.writeHead(404,{"Content-Type":"text/html"});
}
else{
//200:OK
response.writeHead(200,{"Content-Type":"text/html"});
response.write(data.toString());
}
response.end();
});
});
app.listen(3000, function() { //監(jiān)聽(tīng)http://127.0.0.1:3000端口
console.log("server start");
});
在文件地址欄中輸入cmd進(jìn)入命令行,輸入node app.js,然后打開(kāi)localhost:3000/hello.html即可看到html頁(yè)面。
D:\A-Project\webpack\vueAndNode>node app.js
app.use(express.static("public"))這行代碼取的是public文件夾下的今天文件,我這里放了vue,js ,vue.png和common.css文件來(lái)做測(cè)試。
hello.html中的代碼
<html>
<head>
<meta charset="utf-8">
<!-- <script src="https://cdn.jsdelivr.net/npm/vue"></script> -->
<script src="vue.js"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
<link rel="stylesheet" type="text/css" href="common.css"/>
<style>
/* #app {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
color:red;
} */
</style>
</head>
<body>
<div id="app">
{{message}}
<div>
<img src="vue.png" alt="VUElogo" />
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
message: '靜態(tài)資源加載測(cè)試 端口3002!'
}
})
</script>
</body>
</html>
這里引用靜態(tài)文件不需再加public/xxx,如直接引入vue.js
同時(shí)開(kāi)啟端口3001的另一個(gè)項(xiàng)目,引用的vue.js文件也是端口3000的項(xiàng)目中的vue.js
index.html內(nèi)容是類似的,只是引入文件部分換為了
<script src="http://localhost:3000/vue.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:3000/common.css"/>
輸入命令node app.js
打開(kāi)http://localhost:3001/hello.html",

image.png
致此實(shí)現(xiàn)了利用express開(kāi)啟靜態(tài)文件服務(wù)器。