`express.static()`继续从路由中路由我的文件 [英] `express.static()` keeps routing my files from the route

查看:99
本文介绍了`express.static()`继续从路由中路由我的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理快递项目时,我试图使用express.Router对象处理我的应用程序路线.在我的主应用程序文件中,我为所有静态文件(css,javascript,html)添加了一条静态路由.

While working on an express project, I am trying to use an express.Router object to handle my application routes. In my main app file, I have added a static route for all my static files(css, javascript, html).

var express = require('express');
var io = require('socket.io')(app);
var bodyParser = require('body-parser');
var router = require('./include/router');

var app = express();
app.use('/', router);
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

io.on('connection', function(socket) {

});

app.listen(3000);

router.js

var express = require('express');
var path = require('path');

var router = express.Router();

router.get('/', function(req, res) {
  res.sendFile('/html/index.html');
});

module.exports = router;

当我尝试访问localhost:3000时,我得到一个404显示Error: ENOENT, stat 'C:\html\index.html'

When I try to access localhost:3000 I get a 404 showing Error: ENOENT, stat 'C:\html\index.html'

此外,当我尝试直接访问静态路由时(我相信是http://localhost:300/html/index.html),但这给了我Cannot GET /html/index.html.

Furthermore, when I try to access the static route directly(http://localhost:300/html/index.html I believe), but that gives me Cannot GET /html/index.html.

这是我的公用文件夹中的树

This is the tree of my public folder


public
├───css
├───hmtl
|   └───index.html
├───img
└───js

我路由错了吗?我该如何解决?

Am I routing this wrong? How can I fix it?

推荐答案

您必须反转路由器的顺序

You must inverse the order of your router

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

意味着您的路由器将首先被调用,如果没有中间件处理请求,则express将调用静态文件,因此,如果您将静态中间件放在首位,则express将首先处理静态文件.

means your router will be called first and, if no middleware handles the request, then express will call static files so, if you put the static middleware first, the express will handle static files first.

还建议将静态中间件放在首位.

It is also recommended to put static middleware first.

对于您的问题,您应该尝试以下操作:

For your problem you should try this:

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

Express会先在public/html文件夹上尝试静态文件,然后再在其余文件(包括public/html)上尝试,我更喜欢将html文件放在public文件夹的根目录或其他文件夹(例如public-html,静态html)

Express will try static files first on public/html folder, then on the rest (including the public/html), i prefer putting html files on the root of public folder or maybe on a different folder (e.g public-html, static-html)

这篇关于`express.static()`继续从路由中路由我的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆