如何解决节点js中的静态文件路径调用
我已经创建了一个服务器端应用程序,可以检索该目录中的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 控制台?
解决方法
该代码不仅仅作为静态文件提供 index.html
,它还提供该目录中任何被请求的文件。正如您在这里暗示的那样:
ember.jpg和tachyons.min.css用于index.html
因此,如果index.html
引用了另外两个文件,那么当您在浏览器中请求index.html
时,您还将请求另外两个文件。当代码满足这些请求时,它将在此处记录到控制台:
console.log(req.url);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。