[英]How to serve folder in 'public' with express
I am trying to serve the login page in my public folder in express, so far i have been unable to do so.我正在尝试在 express 中为我的公共文件夹中的登录页面提供服务,到目前为止我一直无法这样做。 I tried to work the path but I don't know why it does not work.我试图走这条路,但我不知道为什么它不起作用。 What I want to have is that I can have more code in the callback but because of the way it is now I can do that, when I try to make the callback a full function it won't work either.我想要的是,我可以在回调中拥有更多代码,但由于现在的方式,我可以这样做,当我尝试使回调成为完整功能时,它也无法工作。
My folder structure
- root
- server
- server.js
- public
- login
- index.html
const express = require('express'); const app = express(); const path = require('path'); app.listen(4000); console.log('server started\\n'); app.get('/', () => app.use(express.static(__dirname + '/public/login'))); // what i want to have app.get('/', () => { // serve file });
You should mount the static file serving directly when the server starts, not after the first request arrives so this line:你应该在服务器启动时直接挂载静态文件服务,而不是在第一个请求到达之后,所以这一行:
app.get('/', () => app.use(express.static(__dirname + '/public/login')));
has to be:必须:
app.use(express.static(__dirname + '/../public/login'));
You also have to go up one folder as the code is started in the /server/
directory, which can be done with /../
.当代码在/server/
目录中启动时,您还必须上一个文件夹,这可以使用/../
完成。
If you only want to server the index.html from public folder instead of all files in there, what you can do is如果您只想从公共文件夹而不是那里的所有文件为 index.html 提供服务,您可以做的是
app.get('/', (req, res) => res.sendFile('index.html', { root: __dirname + '/../public/login'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.