简体   繁体   English

未捕获到的SyntaxError:react-router中出现意外的令牌<,最后带有斜杠

[英]Uncaught SyntaxError: Unexpected token < in react-router with trailing slash in the end

I am creating a new app with react-router and I've confronted with this follow trouble: When I insert a URL with http://localhost:3000/app/ , trailing slash in the end of URL, it returns the message Uncaught SyntaxError: Unexpected token < , however when I insert the same URL but without trailing slash in the end, http://localhost:3000/app , it works! 我正在使用react-router创建一个新应用,但遇到了以下麻烦:当我在URL末尾插入带有http:// localhost:3000 / app /的URL时,它会返回消息Uncaught SyntaxError: Unexpected token < ,但是当我插入相同的URL但最后没有尾部斜杠http:// localhost:3000 / app时 ,它起作用了!

How can I keep a pattern of not use the trailing slash in the end of URL and redirect all who has this kind to URLs which not have this? 如何保持不使用URL末尾的斜杠的模式,并将所有具有这种类型的URL重定向到不具有该斜杠的URL?

To solve this can make changes in server-side, in this case I am using Node.js and Express.js as my server, with a function to treat the URL and to redirect this to this URL already treated: 要解决此问题,可以在服务器端进行更改,在这种情况下,我使用Node.js和Express.js作为服务器,并具有处理URL并将其重定向到已经处理过的URL的功能:

app.use(function(req, res, next) {
  if (req.path.length > 1 && /\/$/.test(req.path)) {
    var query = req.url.slice(req.path.length)
    res.redirect(301, req.path.slice(0, -1) + query)
  } else {
    next()
  }
});

This function is receiving requisition, response and next matching route as parameters. 此功能正在接收请求,响应和下一个匹配路由作为参数。 If string URL was bigger than one and if the last parameter of this string URL is / , it makes a 301 redirect to this URL without / , else it continuous the call to the next matching route. 如果字符串URL大于一个,并且该字符串URL的最后一个参数是/ ,则不使用/进行301重定向到该URL,否则将继续调用下一个匹配的路由。

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

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