expres--利用 Express 托管静态文件

express(二)

托管静态文件

使用 Express 中的 express.static 内置中间件函数,可以提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件。
**函数特征:**参数为静态资源根路径

express.static(root, [options])

函数使用

const express = require('express');
const app = express();

//使用
app.use(express.static('public'))

列子
新建文件夹如图。
在这里插入图片描述
hello.html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="style.css" />
	</head>
	<body>
		nihao
	</body>
</html>

css:

body{
	background: red;
}

static.js

/*托管静态文件*/
const express = require('express');
const app = express();
//实现静态资源服务
let server = app.use(express.static('public'))//静态资源的根目录
server.listen(8079, '自己电脑ip地址也行', () => {
	console.log('running');
})

启动:static.js
访问:http://自己电脑ip地址:8079/hello.html
hello.html页面出现内容。
静态资源文件夹里的内容都是可以被访问到的。
如:对应每一个文件就可以了。比如http://自己电脑ip地址:8079/style.css;页面时自己设置的样式内容。
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

注意
app.use(’/static’, express.static(‘public’))//static时访问前缀,加了这个访问时要加前缀static/;叫虚拟目录/虚拟路径。
可以多次使用:

app.use(express.static('public'))

let server = app.use(express.static('public'))//静态资源的根目录
app.use(express.static('另一个文件夹'))/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值