简体   繁体   English

如果在单独的文件中提到路由,则express.router会抛出404

[英]express.router throws 404 if routes mentioned in separate file

I am having trouble and have already spent quite a time to figure out the cause but to no avail. 我遇到了麻烦,已经花了很多时间来找出原因,但无济于事。 I have researched and feel like I am doing right but obviously I missing out something. 我已经研究过,觉得自己做得对,但是显然我错过了一些东西。

Here is my app.js: 这是我的app.js:

var express  = require('express');
var app      = express();
var port     = process.env.PORT || 8080;
var bodyParser   = require('body-parser');
var session      = require('express-session');

app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));

// tell the app to parse HTTP body messages
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser()); // read cookies (needed for auth)

//routes
var authRoutes = require('./server/routes/auth');
app.use('/auth', authRoutes);

app.listen(3000, () => {
   console.log('Server is running on http://localhost:3000);
});

And here is the separate auth (routes file): 这是单独的身份验证(路由文件):

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

router.post('/signup', (req, res, next) => {
   console.log("im in");
});

module.exports = router;

After running this, I get 404 response: POST http://localhost:3000/signup 404 (Not Found) 运行此命令后,我得到404响应:POST http:// localhost:3000 / signup 404(未找到)

If I put the routes in app.js file, I get the desired output. 如果将路线放在app.js文件中,则会得到所需的输出。 Can someone please help me figure out what is that I am doing wrong? 有人可以帮我弄清楚我做错了什么吗?

Try http://localhost:3000/auth/signup 尝试http:// localhost:3000 / auth / signup

app.use('/auth', authRoutes); exposes the authRoutes on paths starting with /auth . 在以/auth开头的路径上公开authRoutes

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

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