nodejs 中public文件夹作用初探

本篇博客对比两个nodejs实例,一个实例将index.html放在与index.js相同的文件夹下;而另一个实例则建立一个与index.js同级的public文件夹,index.html放在public中。第二个实例借助语句

app.use(express.static(path.join(__dirname, 'public')));

把所有静态资源(html文件,或者css之类)指定放置到与入口文件index.js同级的public文件夹下,同样实现与实例1的效果。

实例一代码:

 index.js在package.json中被指定为入口文件(相当于C语言的 main.cpp)

var express = require('express');
var app = express();
var path = require('path');

//app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    //res.send('hello!');
    res.sendFile(__dirname + '/index.html');
});

app.listen(8080);

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Web管理平台</title>
</head>
<body>
  <h1>Web管理平台</h1>
</body>
</html>

当本地浏览器访问127.0.0.1:8080时,index.js的sendFile()函数会把index.html发给浏览器。

再看第二个实例。index.js

此时index.html放到了public文件夹里面

同时,index.js的app.use()函数也指定了public文件夹作为存放静态资源的路径。故sendFile()函数自动从public文件夹里寻找html

var express = require('express');
var app = express();
var path = require('path');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.sendFile('/index.html');
});

app.listen(8080);

实例2的效果:

猜你喜欢

转载自blog.csdn.net/liji_digital/article/details/83449045