【发布时间】:2021-02-10 19:18:59
【问题描述】:
我创建了一个服务器端应用程序,可以检索该目录中的 index.html 文件。
代码如下,
const http = require('http')
const fs = require('fs')
const port = process.env.PORT || 1337;
const server = http.createServer(function (req, res){
if(req.url.match(/^\/static/))
return respondStatic(req,res)
return respondNotFound(req,res)
});
server.listen(port)
function respondStatic(req,res){
const filename = `${__dirname}/public${req.url.split('/static')[1]}`
fs.createReadStream(filename)
.on('error',()=> respondNotFound(req,res))
.pipe(res)
console.log(req.url);
}
然后运行程序并将以下 URL 提供给浏览器。 http://localhost:1337/static/index.html
当我看到终端后,我看到以下代码行 console.log(req.url); 为我提供了 3 个输出,如下所示。
/static/index.html
/static/tachyons.min.css
/static/ember.jpg
在那个目录下,有 5 个文件。
chat.css
chat.html
chat.js
ember.jpg
index.html
tachyons.min.css
ember.jpg 和 tachyons.min.css 用于 index.html。
问题是:
虽然我给了 index.html 作为静态文件 为什么其他 2 文件( which 是 /static/tachyons.min.css & /static/ember.jpg 打印为 req.url in 控制台?
【问题讨论】:
标签: javascript html node.js server static-files