express啟用靜態(tài)資源服務(wù)器

利用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ù)器。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容