简体   繁体   English

Express JS路由器有时返回404,有时返回200

[英]Express JS router sometimes returns 404 and sometimes 200

I use angular 2 and express js. 我使用angular 2并表达js。 So for all requests which is not css, images, js, video I send index.html file. 因此,对于不是CSS,图像,js,视频的所有请求,我都会发送index.html文件。 My router code: 我的路由器代码:

router.get(/\/(?!((.*\.html$)|(.*\.css$)|(.*\.mp4)|(.*\.woff)|(.*\.js$)|(.*\.map$)|(.*\.jpg$)|(.*\.jpeg$)|(.*\.png$)|(.*\.gif$))).+$/gmi,
  ensureConnect.ensureLoggedIn({ redirectTo: '/' }),
  function(req, res) {
    res
      .set('Content-Type', 'text/html')
      .sendFile(../dist/index.html);
  });

For root router '/' it works perfect, but if I try open another page (eg '/product/am-0596157134' ) it sometimes open page, but sometimes returns 404 ( Cannot GET /product/am-0596157134 ) 对于根路由器'/',它可以完美工作,但是如果我尝试打开另一个页面(例如'/ product / am-0596157134' ),则有时会打开页面,但有时会返回404( 无法获取/ product / am-0596157134

So I tried to reload page twice and for the 1st reload it returns 404 and for the 2nd one - it returns 200. Here is log: 所以我尝试重新加载页面两次,第一次加载它返回404,第二次加载它返回200。这是日志:

::ffff:127.0.0.1 - - [10/Nov/2016:11:46:24 +0000] "GET /product/am-0596157134 HTTP/1.1" 404 34 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36" :: ffff:127.0.0.1--[10 / Nov / 2016:11:46:24 +0000]“ GET / product / am-0596157134 HTTP / 1.1” 404 34“-”“ Mozilla / 5.0(Macintosh; Intel Mac OS X 10_12_0)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 54.0.2840.71 Safari / 537.36“

::ffff:127.0.0.1 - - [10/Nov/2016:11:46:25 +0000] "GET /product/am-0596157134 HTTP/1.1" 200 2299 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36" :: ffff:127.0.0.1--[10 / Nov / 2016:11:46:25 +0000]“ GET / product / am-0596157134 HTTP / 1.1” 200 2299“-”“ Mozilla / 5.0(Macintosh; Intel Mac OS X 10_12_0)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 54.0.2840.71 Safari / 537.36“

Any ideas why it happens, and how to fix it? 有什么想法为什么会发生,以及如何解决?

TL;DR: remove the g flag from the regular expression. TL; DR:从正则表达式中删除g标志。

When you use /g , the regular expression keeps an internal state (stored in the lastIndex property) to be able to find successive matches. 使用/g ,正则表达式将保持内部状态(存储在lastIndex属性中),以便能够找到连续的匹配项。

In your case, this state is maintained between requests, so for the first request a match is performed, the last index gets updated, and when a new request comes in, matching starts from that last index. 在您的情况下,请求之间保持这种状态,因此对于第一个请求,执行匹配时,将更新最后一个索引,并且当有新请求进入时,匹配将从该最后一个索引开始。 When it doesn't match (and it probably won't), the state it reset and a new request will match again. 如果不匹配(可能不匹配),则重置状态,新请求将再次匹配。

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

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