Learning Node - Express Public folder not working

拈花ヽ惹草 提交于 2019-12-03 05:41:46

The full URL I am trying to request: http://localhost:1337/public/serveme.txt

That's your problem. Anything inside the directory you designate as static content is made available directly from the base URL. You need to request http://localhost:1337/serveme.txt instead.

If you want to only serve static files from /public you can pass a string as the first argument:

application.use("/public", express.static(path.join(__dirname, 'public')));
Dylan Kirkby

From the Express API reference

app.use(express.static(__dirname + '/public'));

This line serves your public folder at your app's root URL, meaning the following requests are valid and don't give a 404 error.

// GET /javascripts/jquery.js // GET /style.css // GET /favicon.ico

app.use takes an optional first argument as well that allows you to specify which request URL you want to serve content at. This first argument defaults to "/", meaning your static content will be served at the base URL. If you want your static content to be served not at the root level, like your code currently does, check out the following example (again taken from the docs)

app.use('/static', express.static(__dirname + '/public'));

This line serves your public folder again, but at your app's /static URL, making the following requests valid without a 404 error.

(Example URL: http://localhost:1337/static/anythingInYourPublicFolder)

// GET /static/javascripts/jquery.js // GET /static/style.css // GET /static/favicon.ico

What URLs are you trying to load? You should not include "public" in your URLs, so curl -v 'http://localhost:1337/ServeMe.txt'.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!