[英]I'm trying to run an Express static middleware from this book, and I cannot see what the example is trying to show
I'm on a section in this book about Express where it mentions express.static to serve files, but each time I run it, I get the code catching when no file is found. 我在这本书的有关Express的一节中提到了express.static来提供文件,但是每次运行它时,都会在找不到文件的情况下捕获代码。 I have made a folder called public and put in an HTML file, and had it both in the project folder and above it but nothing happens other than the message given after it runs the static method call. 我已经建立了一个名为public的文件夹,并放入了HTML文件,并将其放在项目文件夹中及其上方,但是除了运行静态方法调用后给出的消息外,没有任何反应。
The code is: 代码是:
var express = require("express");
var path = require("path");
var http = require("http");
var app = express();
var publicPath = path.resolve(__dirname,"public");
app.use(express.static(publicPath));
app.use(function(request,response){
response.writeHead(200,{"Content-Type":"text/plain"});
response.end("Looks like you didn't find a static file");
});
http.createServer(app).listen(3000);
The book does not give much more explanation. 这本书没有给出更多的解释。 I've never worked with servers. 我从未使用过服务器。 What is going on? 到底是怎么回事?
I ran your sample code and was able to get it to display HTML files created in a public
directory in the project root. 我运行了您的示例代码,并能够显示在项目根目录的public
目录中创建的HTML文件。
Eg. 例如。 public/page.html
could be retrieved at localhost:3000/page.html
可以在localhost:3000/page.html
检索public/page.html
localhost:3000/page.html
If you create an index.html
file in your public directory it will be retrieved at localhost:3000
. 如果在公共目录中创建index.html
文件,它将在localhost:3000
处进行检索。 The index does not need the full .html
extension. 索引不需要完整的.html
扩展名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.