简体   繁体   English

Node,Express - 无法获取路由

[英]Node, Express - CANNOT GET route

I am building an Express app and having some issues with routing. 我正在构建一个Express应用程序并遇到一些路由问题。 My '/' route is working perfectly, however other routes are not. 我的'/'路线工作正常,但其他路线不是。 I've looked into other questions people have posted and these have not resolved my issues. 我已经调查了人们发布的其他问题,这些问题都没有解决我的问题。

I have a routes/index.js file: 我有一个routes / index.js文件:

module.exports = function(app){
  app.use('/', require('./routes/home'));
  app.use('/about', require('./routes/about'));
}

My routes/home.js: - WORKING! 我的路线/ home.js: - 工作!

const express = require('express');
const router = express.Router();

router.get('/', function(req, res) {
   res.render('app/home');
});

module.exports = router;

My routes/about.js: - NOT WORKING! 我的路线/ about.js: - 不工作!

const express = require('express');
const router = express.Router();

router.get('/about', function(req, res) {
   res.render('app/about');
});

module.exports = router;

When I go to '/about' I see this error in the browser - 'Cannot GET /about' 当我转到'/ about'时,我在浏览器中看到了这个错误 - '无法获取/关于'

Both the home.html and about.html files are located in the same views directory. home.html和about.html文件都位于相同的views目录中。

Any help here would be very appreciated! 这里的任何帮助将非常感谢!

let me quote from express doc: 让我引用明文:

A route will match any path that follows its path immediately with a “/”. 路径将立即匹配其路径后面的任何路径“/”。 For example: app.use('/apple', ...) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on. 例如:app.use('/ apple',...)将匹配“/ apple”,“/ apple / images”,“/ apple / images / news”等。 see express doc 见明确的文件

this is "not working" because you set the /about in the app.use and in the router.get . 这是“不工作”,因为您在app.userouter.get设置了/about try to request /about/about and you will see that this is working (just not as you wanted to).. 尝试请求/about/about ,你会发现这是有效的(只是不是你想要的)..

now just change the /about in the routes/about.js then rerun and try to request /about and it will work :) 现在只需更改/aboutroutes/about.js然后重新运行,并试图请求/about ,也将努力:)

Your route is set to /about/about . 您的路线设置为/about/about Change about.js to this: about.js更改为:

const express = require('express');
const router = express.Router();

router.get('/', function(req, res) {
   res.render('app/about');
});

module.exports = router;

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

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