简体   繁体   English

Express.js 中的默认路由

[英]Default route in Express.js

I'm writing an application with node.js and express.我正在用 node.js 和 express 编写一个应用程序。

I have setup a default route as this :我已经设置了一个默认路由:

app.get('/', function(req, res){
  res.sendfile('./views/index.html');
});

This works fine when I goto /localhost:port/当我转到 /localhost:port/ 时,这工作正常

But in the URL when I type anything after that, /localhost:port/blah I get 404 ERROR which makes sense.但是在 URL 之后,当我输入任何内容时, /localhost:port/blah 我得到 404 ERROR,这是有道理的。

I want to setup a default route so that no matter what I type in the URL after localhost:port/ it should all get back the same html file.我想设置一个默认路由,这样无论我在 localhost:port/ 之后输入什么 URL,它都应该返回相同的 html 文件。

I tried changing / to * :我尝试将 / 更改为 * :

app.get('*', function(req, res){
  res.sendfile('./views/index.html');
});

but after I do this I start getting this error in the console and nothing shows up:但在我这样做之后,我开始在控制台中收到此错误,但没有任何显示:

Uncaught SyntaxError: Unexpected token <未捕获的语法错误:意外的标记 <

in all of my Javascript files: :3000/scripts/myscript.js:1在我所有的 Javascript 文件中: :3000/scripts/myscript.js:1

somehow my javascript file show the content of HTML我的 javascript 文件以某种方式显示了 HTML 的内容

===EDIT==== ===编辑====

I used this and it worked fine for first level urls: like loclhost:port/blah我使用了这个,它对第一级 url 工作正常:比如 loclhost:port/blah

app.use(function(req, res){
    res.sendfile('./views/index.html');
});

but when the URLs are multilevel, I see the same problem as described earlier localhost:port/blah/foo The problem here is that router is looking for public directory under /blah folder for all the javascript and CSS files in this case, which does not exist.但是当 URL 是多级时,我看到了与前面描述的相同的问题 localhost:port/blah/foo 这里的问题是路由器正在 /blah 文件夹下为所有 javascript 和 CSS 文件寻找公共目录在这种情况下,不存在。 And it's returning the default HTML file.它返回默认的 HTML 文件。 How do I fix this?我该如何解决?

==================EDIT POSTING THE WHOLE CODE ========================================= ==================编辑发布整个代码 ============================ ==============

var http = require('http');
var express = require('express');
var api = require('./routes/api');
var mongoose = require('mongoose');
var app = express();


mongoose.connect('mongodb://localhost/mydb');

app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);

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

app.get('/api/user/:userid', api.getUserInfo);

app.get('/', function(req, res){
  res.sendfile('./views/index.html');
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

In addition to this, I have an HTML with a myscript linked in it,除此之外,我还有一个带有 myscript 链接的 HTML,

<script type="text/javascript" src="./scripts/myscript.js" ></script>

As stated here , you can add this middleware just after your routing logic:如前所述在这里,你可以只是你的路由逻辑后添加此中间件:

   app.use(function(req, res){
       res.send(404);
   });

You might find this answer also useful.您可能会发现此答案也很有用。

Of course, you need to adapt the res.send() part to meet your needs.当然,您需要调整res.send()部分以满足您的需求。

Add this route at the after of all your previous routes您之前的所有路线之后添加此路线

app.get('*',function (req, res) {
        res.redirect('/');
    });

This will redirect any route not handled to the index "/"这会将任何未处理的路由重定向到索引“/”

With the newer version of express I would suggest using res.sendStatus as res.send has been deprecated.对于较新版本的 express,我建议使用 res.sendStatus,因为 res.send 已被弃用。

Express v3 Express v3

app.use(function(req, res){
   res.send(404);
});

Express v4快递 v4

app.use(function(req, res){
   res.sendStatus(404);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM