我有这样的目录结构
root
private
js
css
index.html
app.js
privateRouter.js
...
在我的index.html中,我使用如下相对路径引用js和css文件:
<link rel="stylesheet" href="css/index.css"/>
<script src="js/index.js"></script>
在服务器端,我有一个专用路由器在提供以下文件之前检查身份验证:
在app.js中:
app.use("/private", privateRouter);
在privateRouter.js中:
router.use((req, res, next) => {
isAuthenticated(req) ? next() : res.redirect("/");
});
router.get('/', function(req, res, next) {
res.sendFile(require('path').join(__dirname + "/private/index.html"));
});
So now if I visit http://mywebsite.com/private
I will get the the index.html, but the request of js/css files from the browser comes back to the server as http://mywebsite.com/js
instead of http://mywebsite.com/private/js
, thus returns file not found.
Alternatively if I serve files statically, the browser knows to request from /private/js
:
app.use("/private", express.static(path.join(__dirname, 'private')));
But I can't server statically because I need to authenticate specific files and not serve all files publicly. And I don't want to have to append private/
before all file references on client side. I don't understand why when serving statically the server knows to use /private
as root but when using a router it uses /
as root.
How can I keep the url as http://mywebsite.com/private
while not having to append private/
in all file references on the client side?
我是express.js的新手,这对我来说也很困难。我认为我从根本上误解了express.js的工作原理。谢谢你的帮助!
您可以使用中间件为内部路由修改请求的URL:
You can also set the base URL using the base tag, which means you only need to specify the base URL once per page.
然后,应将请求发送到:
但是,您仍然需要代码来处理这些路径,否则,您仍然会收到404 not found错误。