nodejs 中public文件夹作用初探

6 篇文章 0 订阅

本篇博客对比两个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的效果:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值