AngularJS路由为不存在的路由隐藏404响应

时间:2013-12-21 03:59:49

标签: http angularjs express single-page-application

我注意到对不存在路径的GET请求不会返回404响应。相反,客户端获得“200 Ok”,AngularJS呈现主视图,并重写/的路径。在服务器日志中将对无意义URI的请求记录为成功。如果我理解正确,问题在于,由于AngularJS处理路由,服务器必须接受任何URI的GET请求,并始终通过为应用程序的客户端提供响应(“200 Ok”或“304 Not Modified”)。 / p>

例如,使用angular-fullstack Yeoman生成器搭建的项目,请求不存在的/unicorn是这样的:

GET /unicorn 200 31ms - 3.29kb
GET /partials/main 304 36ms
GET /api/awesomeThings 304 5ms

处理请求的Express路由如下所示:

// server, last route:
app.get('*', controllers.index);

// controllers:
exports.index = function(req, res) {
  res.render('index');
};

index.jade是应用程序整个客户端的根。

在Github(AngularJS Express seedAngularJS login)上快速查看其他AngularJS / Express项目的服务器端代码后,我发现这是一种常见模式。我想知道是否有更好的方法来处理不存在路径的请求,以便客户端获得真正的HTTP 404响应?

3 个答案:

答案 0 :(得分:0)

您可以使用$ route.otherwise()函数 为了决定如何处理undefined 路线。 如果您仍想显示404消息, 您只需在此函数和快速中设置/404.html路由。

答案 1 :(得分:0)

这实际上是express处理路由 - 而非角度。删除您发现的app.get('*', ...以禁用该功能。

答案 2 :(得分:0)

角度documentation有一个关于路由的部分。此外,此question和此question包含一些与IIS相关的信息,但可以很容易地进行调整以表达。

Html link rewriting
When you use HTML5 history API mode, you will need different links in different browsers, but all you have to do is specify regular URL links, such as: <a href="/some?foo=bar">link</a>

When a user clicks on this link,

In a legacy browser, the URL changes to /index.html#!/some?foo=bar
In a modern browser, the URL changes to /some?foo=bar
In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

Links that contain target element
Example: <a href="/ext/link?a=b" target="_self">link</a>
Absolute links that go to a different domain
Example: <a href="http://angularjs.org/">link</a>
Links starting with '/' that lead to a different base path when base is defined
Example: <a href="/not-my-base/link">link</a>
When running Angular in the root of a domain, along side perhaps a normal application in the same directory, the "otherwise" route handler will try to handle all the URLs, including ones that map to static files.

To prevent this, you can set your base href for the app to <base href="."> and then prefix links to URLs that should be handled with .. Now, links to locations, which are not to be routed by Angular, are not prefixed with . and will not be intercepted by the otherwise rule in your $routeProvider.

Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
相关问题