教你用Node.js搭建本地服务器,并访问本地图片视频等静态资源

5,509 阅读1分钟

废话不多说,先用express搭建一个本地服务

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

app.get('/', (req, res)=>{
    res.send('Hello world');
});

app.listen(8083, ()=>{
    console.log('Server is running at http://localhost:8083')
})

然后在命令行输入node app启动服务

这个时候我们打开浏览器访问http://localhost:8083就能看到hello world了,表示请求成功了如图

在这里插入图片描述
如果我们要访问图片,得先建一个public文件夹把资源放在里面,加上这几行代码

app.get('/img', function (req, res, next) {
    res.sendFile(path.join(__dirname, 'public/2.png'));
})

这个时候我们在浏览器输入http://localhost:8083/img就能访问到图片了

在这里插入图片描述
视频的话也是同样的道理,我们再加上这几行代码

app.get('/air', function (req, res, next) {
    res.sendFile(path.join(__dirname, 'public/lenveo.mp4'));
})

同样的我们用浏览器打开http://localhost:8083/air就能访问到视频了

在这里插入图片描述
另外txt和pdf文件都是可以访问的,完整代码已上传至码云,需要的请点击 完整代码 看到这里如果对你有帮助的话帮忙点个赞吧。