简体   繁体   English

根“/”上的快速路由在 app.get 中不起作用

[英]Express routing on root "/" doesn't work in app.get

I've been having this issue where for some reason the Express route doesn't see my root get function.我一直遇到这个问题,由于某种原因,Express 路由没有看到我的 root get 函数。 I've declared my app.js this way:我已经这样声明了我的app.js

var index = require('./app/routes/index');
var app = express();
app.use('/', index);

Then in my index.js I have my definition this way:然后在我的index.js中,我的定义是这样的:

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

router.get('/', function(req, res, next) {
  console.log('Enter root.');
});

router.get('/something', function(req, res, next) {
  console.log('Enter something.');
});

Express routes into '/something' just fine, but couldn't see '/' .快速路由到'/something'就好了,但看不到'/' Anybody have an idea why it doesn't work?有人知道为什么它不起作用吗? Thanks.谢谢。

Modified based on new info:根据新信息修改:

If you're getting a 304 status back in the browser, that's because the browser has cached the GET request and the server is telling the browser that the page has not been changed so the browser can just use the cached copy.如果您在浏览器中返回 304 状态,那是因为浏览器已缓存 GET 请求,并且服务器告诉浏览器页面尚未更改,因此浏览器只能使用缓存的副本。

You can make the page uncacheable by changing the headers the server sends with the request.您可以通过更改服务器随请求发送的标头来使页面不可缓存。

See Cache Control for Dynamic Data Express.JS and NodeJS/express: Cache and 304 status code and Nodejs Express framework caching for more info.有关更多信息,请参阅动态数据 Express.JSNodeJS/express 的缓存控制:缓存和 304 状态代码Nodejs Express 框架缓存


You show no exports in index.js so this line:您在index.js没有显示exports ,所以这一行:

var index = require('./app/routes/index');

does not accomplish anything.没有完成任何事情。 index is an empty object and thus this: index是一个空对象,因此:

app.use('/', index);

doesn't do anything and, in fact, may even cause an error.不做任何事情,事实上,甚至可能导致错误。


Perhaps what you want is this:也许你想要的是这样的:

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

router.get('/', function(req, res, next) {
  console.log('Enter root.');
});

router.get('/something', function(req, res, next) {
  console.log('Enter something.');
});

// export your router
module.exports = router;

Then, index in your other file will be the router.然后,其他文件中的index将是路由器。

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

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