简体   繁体   中英

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:

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)

If I put the routes in app.js file, I get the desired output. Can someone please help me figure out what is that I am doing wrong?

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

app.use('/auth', authRoutes); exposes the authRoutes on paths starting with /auth .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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