express启用静态资源服务器

2019-02-21  本文已影响0人  微_______凉

利用express开启服务

新建文件夹,包含app.js 与index.html
项目结构


image.png

app.js代码

const express = require('express');
const fs=require("fs");
const app = express();
app.use(express.static("public"));

// 使用fs.readFile打开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() {   //监听http://127.0.0.1:3000端口
    console.log("server start");
});

在文件地址栏中输入cmd进入命令行,输入node app.js,然后打开localhost:3000/hello.html即可看到html页面。
D:\A-Project\webpack\vueAndNode>node app.js

app.use(express.static("public"))这行代码取的是public文件夹下的今天文件,我这里放了vue,js ,vue.png和common.css文件来做测试。
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: '静态资源加载测试   端口3002!'
          }
        })
  </script>
</body>
</html>

这里引用静态文件不需再加public/xxx,如直接引入vue.js

同时开启端口3001的另一个项目,引用的vue.js文件也是端口3000的项目中的vue.js
index.html内容是类似的,只是引入文件部分换为了

<script src="http://localhost:3000/vue.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:3000/common.css"/>

输入命令node app.js
打开http://localhost:3001/hello.html",

image.png
致此实现了利用express开启静态文件服务器。
上一篇 下一篇

猜你喜欢

热点阅读